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

Python编写的Caesar cipher为何部分解密正确、部分解密错误?

凯撒密码解码错误排查

核心问题点

  • 缺少加密输入文本code的定义逻辑,代码中遍历的code变量未赋值,无法正确读取你输入的待解码内容
  • 回绕判断仅覆盖了小写字母场景,未对大写字母、特殊符号做区分处理:
    1. 大写字母解码时会误触发小写字母的回绕逻辑,例如示例中的首字符L是大写,解码后本应得到H,但因为ord('H') < ord('a'),触发了错误的回绕计算,导致首字符丢失、输出内容偏移
    2. 特殊符号(示例中的$、{、%)不需要做字母回绕处理,直接减位移值即可得到目标符号,当前代码对所有字符统一走小写字母回绕逻辑,导致符号解码错误

修复后代码

distance = int(input("Enter the distance value: "))
code = input("Enter the encoded message: ")
plainText = ""
for ch in code:
    ordvalue = ord(ch)
    cipherValue = ordvalue - distance
    # 小写字母回绕
    if 'a' <= ch <= 'z':
        if cipherValue < ord('a'):
            cipherValue += 26
    # 大写字母回绕
    elif 'A' <= ch <= 'Z':
        if cipherValue < ord('A'):
            cipherValue += 26
    # 其他字符直接保留计算结果,不需要回绕
    plainText += chr(cipherValue)
print(plainText)

验证结果

输入编码消息Lipps${svph%、位移值设为4时,运行代码即可输出预期结果Hello world!

内容的提问来源于stack exchange,提问作者Aces Radix

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 06:57:03