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

凯撒密码解码函数模运算异常:奇偶位置偏移不一致求助

凯撒密码解码异常问题排查与修复

问题现象

将文本“civilization”以偏移量5编码得到“hnanqnefynts”,但解码该结果时得到“csvslszktsox”——奇数位置字符解码正确,偶数位置字符偏移了10(如i→s、a→k、n→x)。

错误代码

def caesar(plain_text, shift_amount, cipher_direction):
    text_to_list = list(text)
    output = ''
    operation = 'encoded'
    for letter in text_to_list:
        letter_int = alphabet.index(letter)
        if cipher_direction == 'decode':
            shift_amount *= -1
            operation = 'decoded'
        processed_letter = alphabet[(letter_int + shift_amount) % len(alphabet)]
        output += processed_letter

问题根源

核心bug是循环内部反复修改shift_amount的值:

  • 当cipher_direction为decode时,第一次循环将shift_amount取负(如5→-5)
  • 第二次循环再次执行取负操作,-5变回5
  • 后续循环持续交替正负偏移,导致奇数索引字符用了正确的负偏移,偶数索引字符用了正偏移(等效偏移量为10),完全匹配你观察到的异常现象

此外代码存在参数名不一致问题:函数接收plain_text参数,但内部使用了未定义的text变量。

修复方案

方案1:提前处理偏移量(推荐)

将偏移量的调整逻辑移到循环外部,确保只执行一次:

def caesar(plain_text, shift_amount, cipher_direction):
    text_to_list = list(plain_text)
    output = ''
    operation = 'encoded'
    
    # 仅在循环前处理一次偏移量
    if cipher_direction == 'decode':
        shift_amount = -shift_amount
        operation = 'decoded'
    
    for letter in text_to_list:
        letter_int = alphabet.index(letter)
        processed_letter = alphabet[(letter_int + shift_amount) % len(alphabet)]
        output += processed_letter
    return output

方案2:计算时直接判断方向

不修改原偏移量,在字符处理时根据方向选择加减:

def caesar(plain_text, shift_amount, cipher_direction):
    output = ''
    alphabet_len = len(alphabet)
    for letter in plain_text:
        letter_int = alphabet.index(letter)
        if cipher_direction == 'decode':
            processed_int = (letter_int - shift_amount) % alphabet_len
        else:
            processed_int = (letter_int + shift_amount) % alphabet_len
        output += alphabet[processed_int]
    return output

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 03:54:28