在我的课上,我的任务是创建一个凯撒密码解码器,需要一个字符串的输入,并找到最好的字符串使用字母频率.如果不知道有多大意义,但让张贴的问题:
- 编写一个程序,完成以下工作:首先,它应该读取一行输入,这是编码信息,由大写字母和空格组成,你的程序必须尝试用移位S的所有26个可能值来解码信息;在这26个可能的原始消息中,打印具有最高良好性的消息。为了您的方便,我们将为您预定义变量leterGoodness,这是一个长度为26的列表,等于上面频率表中的值 *
我有这个代码到目前为止:
x = input()
NUM_LETTERS = 26 #Can't import modules I'm using a web based grader/compiler
def SpyCoder(S, N):
y = ""
for i in S:
x = ord(i)
x += N
if x > ord('Z'):
x -= NUM_LETTERS
elif x < ord('A'):
x += NUM_LETTERS
y += chr(x)
return y
def GoodnessFinder(S):
y = 0
for i in S:
if x != 32:
x = ord(i)
x -= ord('A')
y += letterGoodness[x]
return y
def GoodnessComparer(S):
goodnesstocompare = GoodnessFinder(S)
goodness = 0
v = ''
for i in range(0, 26):
v = SpyCoder(S, i)
goodness = GoodnessFinder(v)
if goodness > goodnesstocompare:
goodnesstocompare = goodness
return v
y = x.split()
z = ''
for i in range(0, len(y)):
if i == len(y) - 1:
z += GoodnessComparer(y[i])
print(z)
编辑:根据Cristian Ciupitu的建议进行了修改请忽略缩进错误,它们可能是在我复制代码时出现的。
程序的工作原理如下:
- 获取输入并将其拆分为列表
- 对于每一个列表值,我都将其提供给一个好的发现器。
- 它把字符串的优值和其他值进行比较当优值更高时,它就把更高的优值作为比较对象.
- 然后,它将文本字符串移动i个量,以查看质量是更高还是更低
我不太确定问题出在哪里,第一个测试:LQKP氧气CV GKIJV DA VJG BQQ
打印正确的消息:加入我在动物园
然而下一个测试:UIJT JT B TBNQMF MJOF PG UFYU全球定位系统
为提供一个垃圾字符串:新加坡人力资源部Z RZLOKD KHMD NE软件数据表查询CDBQXOSHMF
当它应该是:这是用于解密的文本示例行
我知道我必须:
尝试每个偏移值
领会这个词的“善”
返回具有最高优值的字符串。
我希望我的解释是有道理的,因为我现在很困惑。
5条答案
按热度按时间qaxu7uf21#
下面是我的实现,它运行良好。
你应该打印出每一条可能的消息的优点,看看为什么你的程序输出它。
kkbh8khc2#
我最后的解决方案是有效的,感谢出色的克里斯蒂安·丘皮图。
谢谢你所有的帮助!
ajsxfq5m3#
我正在编写同一个教程,但使用了一个稍微不同的方法,这样就避免了创建和调用函数:
请注意,此代码的许多部分可以(也应该)进行压缩,例如
它们被扩展到“显示我的工作”,作为教程练习。
nkoocmlb4#
dly7yett5#