gpt4 book ai didi

python - 我的 Python 凯撒密码程序在 30 后停止移动

转载 作者:行者123 更新时间:2023-12-02 02:06:51 25 4
gpt4 key购买 nike

我创建了一个函数,将输入的字符串拆分为单词列表,然后将每个单词中的字母替换为移位后的对应字母,但是当我将移位设置为超过 30 时,它的打印结果保持不变。

def ceaser_cipher_encoder(string , num):
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"]

new_string = ""
string_list = string.split(" ")
new_list = []
for word in string_list:
word1 = ""
for charecter in word:
letter_position = alphabet.index(charecter)
letter_position_with_shift = letter_position + num
if letter_position_with_shift > 25:
letter_position_with_shift = 0 + ((letter_position - 25) - 1)
word1 += charecter.replace(charecter, alphabet[letter_position_with_shift])

new_list.append(word1)
end_string = " ".join(new_list)



return end_string




message = ceaser_cipher_encoder("hello dad", 35)
print(message)

最佳答案

这里的一个有用技巧是使用运算符(%)。它会为您处理轮类。

这是我会做的:

def ceaser_cipher_encoder(string , num):
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"]

new_string = ""
for c in string:
new_string += alphabet[(alphabet.index(c) + num) % len(alphabet)]
return new_string

假设 c 是“y”,num 是 10。那么 alphabet.index(c) 等于 24,因此移位将返回 34。由于 34 模 26 为 8,因此会将 alphabet[8] ("i") 附加到 new_string

我使用 len(alphabet) 而不是硬编码 26,以便您可以更改字母表并且代码仍然有效。

关于python - 我的 Python 凯撒密码程序在 30 后停止移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68316900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com