【问题标题】:perofrming caesarcipher for a string using shift使用 shift 为字符串执行 caesarcipher
【发布时间】:2022-12-10 16:31:26
【问题描述】:
from string import ascii_lowercase as alphabet1
from string import ascii_uppercase as alphabet2

import letter as letter



def cipher(user_input, shift):
    cipher1 = {char: alphabet1[(i + shift) % 26] for i, char in enumerate(alphabet1)}
    cipher2 = {char: alphabet2[(i + shift) % 26] for i, char in enumerate(alphabet2)}
    
    caesar_cipher = ""
    
    for letter in user_input:
        caesar_cipher += cipher1.get(letter, letter)
    else:
        caesar_cipher += cipher2.get(letter, letter)
    return caesar_cipher


if __name__ == "__main__":
    
    user_input = input("Enter the String: ")
    
    shift = int(input("Enter shift: "))
    
    print("Caesar Cipher: " + cipher(user_input, shift))

我正在为大写和小写字符执行 Caeser 密码。 但结果不正确。 cipher1 用于小写,密码 2 用于大写。我已经在函数中定义了它。并在 main 方法中调用它 小写得到的结果是:

Enter the String: abc
Enter shift: 2
Caesar Cipher: cdec

应该是cde

大写得到的结果是:

Enter the String: ABC
Enter shift: 2
Caesar Cipher: ABCE

应该是CDE

【问题讨论】:

标签: python caesar-cipher


【解决方案1】:

检查每个字母是大写还是小写,然后使用相应的密码。

    ...
    
    for letter in user_input:
        cipher = cipher1 if letter in cipher1 else cipher2
        print(cipher[letter])

c
D
e

当迭代器耗尽时,执行 else 子句中的套件(如果存在),然后循环终止。

您的 else 子句始终在执行。


For loop

【讨论】:

  • 我需要从用户那里获取输入。你能不能只修改上面的代码@wwii
  • 谢谢你的帮助,我明白了。
【解决方案2】:
from string import ascii_lowercase as alphabet1
from string import ascii_uppercase as alphabet2

import letter as letter



def cipher(user_input, shift):
    cipher1 = {char: alphabet1[(i + shift) % 26] for i, char in enumerate(alphabet1)}
    cipher2 = {char: alphabet2[(i + shift) % 26] for i, char in enumerate(alphabet2)}
    
    caesar_cipher = ""
    
    for letter in user_input:
        caesar_cipher += cipher1.get(letter, letter)
    else:
        caesar_cipher += cipher2.get(letter, letter)
    return caesar_cipher


if __name__ == "__main__":
    
    user_input = input("Enter the String: ")
    
    shift = int(input("Enter shift: "))
    
    print("Caesar Cipher: " + cipher(user_input, shift))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-04
    • 2011-11-10
    • 2018-12-05
    • 1970-01-01
    • 2012-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多