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

实现移位密码时,如何在列表末尾循环回到开头?

解决移位密码的循环计数问题

核心解决方法是用**模运算(%)**处理索引越界,因为字母表共26个元素,模26后会自动从开头循环计数。

具体步骤

  1. 获取原字母在列表中的索引:original_index = alphabet.index(char)
  2. 计算移位后的新索引:new_index = (original_index + shift) % len(alphabet)
    • 当original_index + shift小于26时,模运算结果就是本身,正常取值;
    • 当结果大于等于26时,模26会得到0-25之间的余数,实现从开头继续计数。

错误公式说明

你之前尝试的alphabet[len(alphabet) - (len(alphabet) - shift -1)]化简后等价于alphabet[shift + 1],完全没考虑原字母的位置,所以无法得到正确结果。

完整示例代码

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

def shift_cipher(word, shift):
    encrypted = []
    for char in word.lower():
        if char in alphabet:
            orig_idx = alphabet.index(char)
            new_idx = (orig_idx + shift) % 26
            encrypted.append(alphabet[new_idx])
        else:
            encrypted.append(char)  # 保留非字母字符
    return ''.join(encrypted)

# 测试用例
print(shift_cipher('hello', 5))  # 输出 mjqqt
print(shift_cipher('xyz', 3))    # 输出 abc

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 02:55:59