我了解凯撒密码方法,并成功地使用模运算符编写了我自己的概括,但我不了解我正式学习课本中所示的方法。我指的是我在下面评论的代码:
plainText = input("Enter a one-word, lowercase message: ")
distance = int(input("Enter the distance value: "))
code = ""
for ch in plainText:
ordvalue = ord(ch)
cipherValue = ordvalue + distance
#confusion begins here
if cipherValue > ord('z'):
cipherValue = ord('a') + distance - \
(ord('z') - ordvalue + 1)
#confusion ends here
code += chr(cipherValue)
print(code)
如果你想一想,它是有意义的,即使它是一个稍微冗长和复杂的计算方法。唉,表达的复杂程度没有限制,只有表达的简单程度
所以
ord('a')
和ord('z')
的值是97和122。当我们得到ord(char) + distance = 123,
时,我们想把它映射回ord('a')
,对吧。所以我们需要减去允许的字符间隔的长度。此间隔的大小为ord('z') - ord('a') + 1
(+1,因为两个端点实际上都是间隔和允许值的一部分)结果公式为(假设
ordValue + distance > ord('z')
)。。。这是让你困惑的表达
最后,此方法存在一个陷阱,即它最多只覆盖
ord('z') - ord('a') + 1
的溢出,因此如果distance
比这长,它将无法工作:现在,如果
ordValue
来自ord('z')
,那么我们就有麻烦了,因为密码值将是ord('z') + 1 = 123
,它与密文字母表中的字符(chr(123) = '{'
)不对应也许我们可以假设
distance
不应该那么长或更长(这是有道理的),否则使用模表达式会更安全相关问题 更多 >
编程相关推荐