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

Vigenère密码解码代码输出不符预期,请求排查与修复

Vigenère密码解码错误修复

问题根源

你的代码核心错误是:关键字的循环计数没有跳过非字母字符。Vigenère密码规则中,只有处理字母字符时才会使用关键字的下一个字符;空格、标点这类非字母字符不消耗关键字的位置,应直接保留。但你的代码用整个消息的索引i来计算关键字位置,导致非字母字符也会让关键字循环,最终偏移量计算全部错误。

修复后的代码

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"]

v_message= "txm srom vkda gl lzlgzr qpdb? fepb ejac! ubr imn tapludwy mhfbz cza ruxzal wg zztylktoikqq!"

keyword = "friends"

def vigenere_cipher(message, keyword):
    decoded = []
    key_pos = 0  # 单独维护关键字的位置,仅处理字母时递增
    keyword_len = len(keyword)
    for char in message:
        if char.isalpha():
            char_index = alphabet.index(char)
            key_index = alphabet.index(keyword[key_pos % keyword_len])
            letter_index = (char_index - key_index) % len(alphabet)
            decoded.append(alphabet[letter_index])
            key_pos += 1  # 只有处理字母时,关键字位置才前进
        else:
            decoded.append(char)
    return "".join(decoded)

print(vigenere_cipher(v_message, keyword))

修复说明

  • 新增key_pos变量,专门记录当前使用的关键字字符位置,初始值为0。
  • 遍历消息字符时,仅在处理字母字符时递增key_pos,确保非字母字符不消耗关键字的循环位置。
  • 用key_pos % keyword_len获取当前关键字的索引,替代原代码中基于整个消息索引的计算方式。

正确输出

运行修复后的代码,会得到正确解密结果:

you were able to decode this? nice work! you are becoming quite the expert at cryptography!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 00:10:09