凯撒密码代码字母移位异常:单字符正常整词解码错误求助
凯撒密码解密异常问题排查与修复
问题现象
学习凯撒密码课程时,复制课程提供的代码运行出现异常:
- 单个字母解密正常:选择decode模式,对字母'C'设置偏移量2,可正确得到'a'
- 整词解密错误:对'khoor'设置偏移量3解密,预期输出'hello',实际得到'hklro'
原代码
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(encode_or_decode,original_text, shift_amount): output_text = "" for letter in original_text: if encode_or_decode == "decode": shift_amount *= -1 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)
测试输入
"decode", "khoor", "3"
问题原因
核心错误在于caesar函数的循环逻辑:每次遍历字母时都会执行shift_amount *= -1,导致偏移量在每次迭代中反复正负切换。以解密'khoor'为例:
- 第一个字母'k':shift变为-3,计算后得到'h'(正确)
- 第二个字母'h':shift变回3,计算后得到'k'(错误,本该是'e')
- 第三个字母'o':shift又变为-3,计算后得到'l'(正确)
- 第四个字母'o':shift变回3,计算后得到'r'(错误,本该是'l')
- 第五个字母'r':shift变为-3,计算后得到'o'(正确)
最终拼接出错误结果'hklro'
修复方案
将偏移量调整逻辑移到循环外部,仅在函数开始时根据模式设置一次偏移量,避免每次循环反复修改:
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(encode_or_decode,original_text, shift_amount): 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)
修复后运行测试输入,即可正确得到'hello'。
内容的提问来源于stack exchange,提问作者Gusm98
相关产品推荐
相关产品推荐

