Python 具有所需功能的Vigenere密码

Python Vigenere Cipher with required functions

我正在开设一个在线课程,该课程要求我们创建凯撒密码和维吉尼亚密码,但我们首先创建了两个函数;一个是在字母表变量中找到一个字母的位置,另一个是将一个给定的字符旋转给定的次数(我已经看到 ord() 和 chr() 工作得更好,但作业希望我们专注于更简单的概念现在,我猜)。

我能够使 caesar 函数正常工作,但不确定如何继续使用 vigenere 密码。我看了很多视频并浏览了这个网站,但没有找到任何允许保留空格和非字母字符的视频。任何人都可以指出如何启动 vigenere 功能的正确方向吗?

#Create function alphabet_position(letter) to turn letter into number
#such as a=0 or e=4, using lowercase to make sure case doesnt matter.
def alphabet_position(letter):
    alphabet ="abcdefghijklmnopqrstuvwxyz" #Lists alphabet for a key
    lower_letter = letter.lower()   #Makes any input lowercase.
    return alphabet.index(lower_letter) #Returns the position of input as a number.

def rotate_character(char, rot):
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    if char.isalpha():
        a = alphabet_position(char)
        a = (a + rot) % 26            #needs modulo
        a = (alphabet[a])
        if char.isupper():
            a = a.title()
        return a
    else:
       return char

def encrypt(text, rot):
    list1 = ""
    for char in text:
        list1 += rotate_character(char, rot)
    return list1



def main():
    x = input("Type a message: ")
    y = input("Rotate by: ")
    #result = rotate_character(x, y)  #Not needed once encrypt function works.
    result = encrypt(x, y)
    print (result)

if __name__ == '__main__':
    main()

关注我的评论;使用所有印刷品作为字母表:

from string import ascii_letters, digits, punctuation, whitespace

ALPHABET = ascii_letters + digits
STATIC_ALPHABET = punctuation + whitespace

# minor speedup
ALPHA_INDEX = {a: i for i, a in enumerate(ALPHABET)}
STATIC_ALPHABET_SET = set(STATIC_ALPHABET)
MOD = len(ALPHABET)

def encrypt(char, key):
    if char in STATIC_ALPHABET_SET:
        return char
    else:
        return ALPHABET[(ALPHA_INDEX[char] + key) % MOD]

def decrypt(char, key):
    if char in STATIC_ALPHABET_SET:
        return char
    else:
        return ALPHABET[(ALPHA_INDEX[char] + MOD - key) % MOD]

key = 17
plain = 'Hello World!'
enc = ''.join(encrypt(char, key) for char in plain)
print(enc)  # YvCCF dFICu!
dec = ''.join(decrypt(char, key) for char in enc)
print(dec)  # Hello World!