所以我一直在做一个作业,使用创建一个凯撒和维格纳密码。我已经发明了凯撒密码,维格纳也快完成了。我遇到的问题是加密本身。在我的代码中,我已经把标点符号和大写字母都处理好了,但是当我只是用print测试我的函数时,它只是把同样的短语吐回给我。我不确定问题是我的函数在遍历函数的其余部分之前读取关键字,还是我错过了什么。任何帮助都将不胜感激!在
def alphabet_position(letter):
alphabet_pos = {'A':0, 'a':0, 'B':1, 'b':1, 'C':2, 'c':2, 'D':3,
'd':3, 'E':4, 'e':4, 'F':5, 'f':5, 'G':6, 'g':6, 'H':7, 'h':7, 'I':8,
'i':8, 'J':9, 'j':9, 'K':10, 'k':10, 'L':11, 'l':11, 'M':12, 'm':12,
'N': 13, 'n':13, 'O':14, 'o':14, 'P':15, 'p':15, 'Q':16, 'q':16,
'R':17, 'r':17, 'S':18, 's':18, 'T':19, 't':19, 'U':20, 'u':20, 'V':21,
'v':21, 'W':22, 'w':22, 'X':23, 'x':23, 'Y':24, 'y':24, 'Z':25, 'z':25
}
pos = alphabet_pos[letter]
return pos
def rotate_character(char, rot):
if (ord(char) >= 97) and (ord(char) <= 122): # lowercase
return chr(97+(alphabet_position(char)+rot)%26)
elif (ord(char) >= 65) and (ord(char) <=90): # uppercase
return chr(65+(alphabet_position(char)+rot)%26)
else:
return char
def encrypt(text, key):
encrypted = []
starting_index = 0
for letter in text:
# if it's alphanumerical, keep it that way
# find alphabet position
rotation = alphabet_position(key[starting_index])
# if it's a space or non-alphabetical character, append and move on
if letter != alphabet_position:
encrypted.append(letter)
elif letter.isalpha():
encrypted.append(rotation(letter, rotation))
#if we've reached last index, reset to zero, otherwise + by 1
if starting_index == (len(key) - 1):
starting_index = 0
else:
starting_index += 1
return ''.join(encrypted)
你的问题在于:
由于字母表位置是一个函数,它总是与字母不同。因此,执行下一条指令,它将
letter
作为结果的附加。在这条线:
不判断
letter
是否为字母。它只是将letter
(字符串)的值与alphabet_position
(函数)的值进行比较,它们永远不会相等。所以它总是运行那个代码块,它只是将字母添加到encrypted
。在您可以使用
^{pr2}$string.isalpha()
函数来执行此操作。在也可以将
alphabet_pos
字典设为全局变量,并使用:相关问题 更多 >
编程相关推荐