列表索引越界问题:凯撒密码循环移位时z字母处理方案咨询
解决凯撒密码移位中字母循环的索引越界问题
你的代码在处理z这类末尾字母时会触发IndexError,原因是计算后的新索引超出了alphabet列表的最大范围(索引0-25)。要实现移位到末尾后从开头循环的效果,只需要用模运算对新索引取余即可。
原代码
def encrypt(plain_text, shift_amount): cipher_text = "" for letter in plain_text: position = alphabet.index(letter) new_position = position + shift_amount cipher_text += alphabet[new_position] print(f"The encoded text is {cipher_text}") encrypt(plain_text=text, shift_amount=shift)
报错信息
error:
Traceback (most recent call last):
File "\caesar-cipher\caesar-cipher-4 Final.py", line 36, in
encrypt(plain_text=text, shift_amount=shift)IndexError: list index out of range
修改后的代码
def encrypt(plain_text, shift_amount): 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'] cipher_text = "" for letter in plain_text: position = alphabet.index(letter) # 模运算确保索引始终在0-25区间,实现循环移位 new_position = (position + shift_amount) % len(alphabet) cipher_text += alphabet[new_position] print(f"The encoded text is {cipher_text}") # 测试示例 encrypt(plain_text="hello", shift_amount=5) # 输出: The encoded text is mjqqt encrypt(plain_text="z", shift_amount=5) # 输出: The encoded text is e
原理说明
len(alphabet)的值是26,任何整数对26取余都会得到0到25之间的结果:
- 比如
z的索引是25,移位5位后计算得25+5=30,30%26=4,对应alphabet[4]就是e,完美实现循环。 - 即使
shift_amount远大于26(比如30),模运算会自动转换成等价的小数值(30%26=4),结果和移位4位一致,无需额外处理大数值移位。
内容的提问来源于stack exchange,提问作者Hershey
相关产品推荐
相关产品推荐

