我的python caeser密码程序在30秒后停止移动

dwbf0jvd  于 2021-09-08  发布在  Java
关注(0)|答案(3)|浏览(320)

我创建了一个函数,将输入的字符串拆分为单词列表,然后用移位后的对应项替换每个单词中的字母,但当我将移位设置为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)
cnh2zyt3

cnh2zyt31#

这里一个有用的技巧是使用模运算符( % ). 它会帮你安排班次的。
我会这样做:

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,这样你可以改变你的字母表和代码仍然会工作。

4sup72z8

4sup72z82#

问题在于您的if语句:

if letter_position_with_shift > 25:
    letter_position_with_shift = 0 + ((letter_position - 25) - 1)

应该是:

if letter_position_with_shift > 25:
    letter_position_with_shift = 0 + ((letter_position_with_shift - 25) - 1)

也就是说,这里最好使用modolo运算符而不是if语句来处理26的任意倍数,而不仅仅是26-52。
尝试将for循环体更改为:

letter_position = alphabet.index(charecter)
letter_position_with_shift = (letter_position + num) % 26
word1 += charecter.replace(charecter, alphabet[letter_position_with_shift])

我还建议将最后一行替换为:

word1 += alphabet[letter_position_with_shift]

因为你要把那封信附在 word1 无论如何,您不需要对字符调用replace来获取字母表[字母\u位置\u随\u移位]

zzwlnbp8

zzwlnbp83#

如果您想让代码稍微短一点,可以尝试以下方法:

def cipher(plain: str, offset: int) -> str:
    abc = 'abcdefghijklmnopqrstuvwxyz'
    return plain.translate(str.maketrans({c: abc[(idx + offset) % len(abc)] for idx, c in enumerate(abc)}))

print(cipher("hello dad", 35))  # Output: qnuux mjm

进一步阅读:
听写理解 str.translate str.maketrans enumerate

相关问题