You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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) 

问题产生原因

重复输出的核心原因是嵌套循环的匹配逻辑存在重复匹配问题:

  1. 存储的alphabet列表包含2组a~z字母,同一个字母会在列表中出现2次
  2. 现有逻辑对输入文本的每个字符i,都会完整遍历整个alphabet列表做相等判断,只要匹配到相同字母就追加一次移位结果
  3. 因此每个输入字符会先后匹配到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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 14:21:07