首页 > 解决方案 > Python 中的凯撒密码求解器

问题描述

我在 python 中做了一个凯撒密码求解器,但是没有错误,它只是没有打印任何东西。我做过类似的事情,但以前没有发生过。

with open("C:\\Users\\Rajive\\AppData\\Local\\Programs\\Python\\Python3.4.3\\brit-a-z.txt", 'r') as f:
    check_list = [x.strip() for x in f.readlines()]

def crackcaesar(encrypted):
    for i in range(26):
        totalwords = 0
        numright = 0
        answer = []
        if i != 0: 
            for symbol in encrypted:
                if symbol.isalpha():
                    neword = (ord(symbol) + i)
                    if symbol.isupper():
                            if neword > ord('Z'):
                                neword -= 26
                            elif neword < ord('A'):
                                neword += 26
                    elif symbol.islower():
                         if neword > ord('z'):
                             neword -= 26
                         elif neword < ord('a'):
                             neword += 26
                    newletter = chr(neword)
                    answer.append(newletter)
                    for word in str(answer):
                        totalwords += 1
                        for line in check_list:
                            if line == word:
                                numright += 1
        if (numright // 2) > (totalwords // 2):
            print(str(answer))

print("Type your encoded caesar cipher message")
while True:
    crackcaesar(input())

标签: pythonpython-3.xcaesar-cipher

解决方案


问题是numright永远不会大于totalwords。尝试

if numright == totalwords:
    print(str(answer))

另外,answer是一个字符列表。 str(answer)会给你"['a', 'b', 'c']"。你需要使用"".join(answer).


推荐阅读