Python实现Caesar Cipher时for循环输出加密结果重复两次
凯撒密码输出重复问题排查与修复
问题背景
- 功能预期:实现凯撒密码加解密逻辑,对用户输入的文本按指定偏移量移位,例如偏移量为1时输入
abc应输出bcd - 前置设计:将a~z字母表重复拼接两次存储,避免对z这类末尾字母做移位时触发索引越界错误
- 异常现象:所有加密输出的字符均重复1次,实际输出长度为预期的2倍,测试用例表现:
- 输入
abc,预期输出bcd,实际输出bbccdd - 输入
zulu,预期输出avmv,实际输出aavvmmvv
- 输入
问题实现代码如下:
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', '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") text = input("Type your message:\n").lower() shift = int(input("Type the shift number:\n")) def encrypt(text, shift): cipher_text = "" for i in text: for letter in alphabet: if i == letter: index = alphabet.index(letter) shifted_index = index + shift shifted_letter = alphabet[shifted_index] cipher_text += shifted_letter print(f"The encoded word is {cipher_text}") encrypt(text, shift)
问题产生原因
重复输出的核心原因是嵌套循环的匹配逻辑存在重复匹配问题:
- 存储的
alphabet列表包含2组a~z字母,同一个字母会在列表中出现2次 - 现有逻辑对输入文本的每个字符
i,都会完整遍历整个alphabet列表做相等判断,只要匹配到相同字母就追加一次移位结果 - 因此每个输入字符会先后匹配到
alphabet里2个位置相同的字母,触发2次追加操作,最终输出的每个字符都会重复一次。
修复方案
删除冗余的内层遍历alphabet的循环,直接通过alphabet.index(i)获取字符在字母表中第一次出现的位置即可,既可以避免重复匹配,还能提升代码运行效率。
额外优化建议:为了避免输入的shift值超过26导致索引越界,可以对shift值做shift % 26取模处理,兼容任意大小的偏移量输入。
修复后的完整代码:
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', '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") text = input("Type your message:\n").lower() shift = int(input("Type the shift number:\n")) # 偏移量取模,兼容大于26的偏移输入 shift = shift % 26 def encrypt(text, shift): cipher_text = "" for i in text: # 直接获取字符索引,无需遍历整个字母表 index = alphabet.index(i) shifted_index = index + shift shifted_letter = alphabet[shifted_index] cipher_text += shifted_letter print(f"The encoded word is {cipher_text}") encrypt(text, shift)
修复后测试验证:
- 输入
abc、偏移量1,输出bcd,符合预期 - 输入
zulu、偏移量1,输出avmv,符合预期
内容的提问来源于stack exchange,提问作者Omar Mohamed
相关产品推荐
相关产品推荐

