试图包装凯撒密码 (Python)

Trying to wrap caesar cypher (Python)

我试过使用“if”语句来跳过非字母顺序的字符,但它总是忽略代码并添加移位的字符。我正在尝试将用户输入移位 2,但编码字不应该有任何特殊字符,因此移位将从 z-a 回绕。

下面的代码是在我尝试“if”语句之前。

encoded_word = ("")
decoded_word = ("")

def Encoding(text):
    global encoded_word
    letter_list = list(text)
    length_list = len(text) 
    for i in range (0,length_list):
        letter_ord = ord(letter_list[i])
        encoded_letter = chr(letter_ord+2)
        encoded_word = (encoded_word + encoded_letter)
    print ("The encoded word is now:",encoded_word)

def Decoding(text):
    global decoded_word
    letter_list = list(text)
    length_list = len(text) 
    for i in range (0,length_list):
        letter_ord = ord(letter_list[i])
        decoded_letter = chr(letter_ord-2)
        decoded_word = (decoded_word + decoded_letter)
    print ("The decoded word is:",decoded_word)

decode_encode = str(input("Would you like to encode or decode text? encode/decode: "))
if decode_encode == "encode":
    user_word = str(input("Enter in a word to encode: "))
    Encoding(user_word)
if decode_encode == "decode":
    user_word = str(input("Enter in the encoded word: "))
    Decoding(user_word)

要检查字符是否为字母,您可以使用 isalpha()。 例如应该只打印 d 和 f:

    list = ["3","2","-","1","4","5","-","3","d", "f"]
    character_list = []

    for i in list:
        if i.isalpha():
            character_list.append(i)
        
    print (character_list)

问题是,当加减 2 时,您没有检查是否达到了字母表的限制('a' 或 'z')。你应该做类似

的事情
if encoded_letter > "z":
   # do something

您采用的方法不是最好的方法。但是,假设您只考虑小写字符。

编码

正在替换

encoded_letter = chr(letter_ord + 2)

encoded_ord = letter_ord + 2
if encoded_ord > ord('z'):  # after encoding if exceeds from 'z'
    difference = encoded_ord - ord('z')  # finding how much exceeded from 'z'
    encoded_ord = ord('a') + difference + 1  # restart from 'a' again.
encoded_letter = chr(encoded_ord)

解码

正在替换

decoded_letter = chr(letter_ord-2)

decoded_ord = letter_ord - 2        
if decoded_ord < ord('a'):     # after decoding if deceeds from 'a'
    difference = ord('a') - decoded_ord   # finding how much deceeded from 'a'
    decoded_ord = ord('z') - difference + 1   # restart from 'z' again but backward
decoded_letter = chr(decoded_ord)

应该可以

我认为你在正确的轨道上,你只是为了处理更多的边缘情况,例如移位量是否大于 26,或者移位是否需要回绕等。此外,字符串连接使用+ 效率低下,因为每次连接都需要复制现有字符串。因此,考虑改为附加到字符列表,并只在末尾创建输出 encoded/decoded 字符串:

SHIFT_AMOUNT = 2

def encode(text):
    res = []
    actual_shift_amount = SHIFT_AMOUNT % 26
    for ch in text:
        new_letter = ch
        if ord('a') <= ord(ch) <= ord('z'):
            if (ord(ch) + actual_shift_amount) <= ord('z'):
                new_letter = chr(ord(ch) + actual_shift_amount)
            else:
                new_letter = chr(ord('a') + actual_shift_amount - (ord('z') - ord(ch) + 1))
        elif ord('A') <= ord(ch) <= ord('Z'):
            if (ord(ch) + actual_shift_amount) <= ord('Z'):
                new_letter = chr(ord(ch) + actual_shift_amount)
            else:
                new_letter = chr(ord('A') + actual_shift_amount - (ord('Z') - ord(ch) + 1))
        res.append(new_letter)
    return ''.join(res)

def decode(text):
    res = []
    actual_shift_amount = SHIFT_AMOUNT % 26
    for ch in text:
        new_letter = ch
        if ord('a') <= ord(ch) <= ord('z'):
            if (ord(ch) - actual_shift_amount) >= ord('a'):
                new_letter = chr(ord(ch) - actual_shift_amount)
            else:
                new_letter = chr(ord('z') - actual_shift_amount + (ord(ch) - ord('a') + 1))
        elif ord('A') <= ord(ch) <= ord('Z'):
            if (ord(ch) - actual_shift_amount) >= ord('A'):
                new_letter = chr(ord(ch) - actual_shift_amount)
            else:
                new_letter = chr(ord('Z') - actual_shift_amount + (ord(ch) - ord('A') + 1))
        res.append(new_letter)
    return ''.join(res)


decode_or_encode = input("Would you like to encode or decode text? encode/decode: ").lower()
if decode_or_encode == "encode":
    user_word = input("Enter in a word to encode: ")
    print(encode(user_word))
elif decode_or_encode == "decode":
    user_word = input("Enter in the encoded word: ")
    print(decode(user_word))

用法示例encode:

Would you like to encode or decode text? encode/decode: encode
Enter in a word to encode: Yoruke-Stack-Overflow
Aqtwmg-Uvcem-Qxgthnqy

用法示例decode:

Would you like to encode or decode text? encode/decode: decode
Enter in the encoded word: Aqtwmg-Uvcem-Qxgthnqy
Yoruke-Stack-Overflow

试一试here.