如何修复凯撒密码(Caesar Cipher)的解密异常问题?
凯撒密码解密错误的修复方案
你的代码加密功能正常,但解密时结果错误,问题出在循环内部重复修改shift_amount的值:
当执行解密时,每遍历一个字母就会执行shift_amount *= -1,导致移位值在正负之间来回切换。比如解密"pq"(移位2):
- 处理第一个字母p:shift从2变为-2,计算后得到n(正确)
- 处理第二个字母q:shift又从-2变回2,计算后得到s(错误)
最终结果就变成了"ns"而非预期的"no"
修复方法
将对shift_amount取反的逻辑移到循环外部,只执行一次:
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n").lower() text = input("Type your message:\n").lower() shift = int(input("Type the shift number:\n")) def caesar(original_text, shift_amount, encode_or_decode): output_text = "" # 只在函数开头调整一次移位方向 if encode_or_decode == "decode": shift_amount *= -1 for letter in original_text: shifted_position = alphabet.index(letter) + shift_amount shifted_position %= len(alphabet) output_text += alphabet[shifted_position] print(f"Here is the {encode_or_decode}d result: {output_text}") caesar(original_text=text, shift_amount=shift, encode_or_decode=direction)
修复逻辑说明
解密时,我们只需要把移位值取反一次,之后所有字母都使用这个统一的负移位值进行计算,这样每个字母都会正确地反向移位,解密"pq"时就能得到正确的"no"。
内容的提问来源于stack exchange,提问作者Hjortlund
相关产品推荐
相关产品推荐

