我具有以下凯撒代码功能:我希望能够撤消密码并返回原始单词,我在这里为单词“ hello”工作,它将单词“ xvdei”密码化,并将其解密为“你好”。但是,它对我输入的其他任何字词均无效,我想知道如何编辑该字词,以便我输入的任何字词都可以解密为原始字词。因此,就像我输入xvdei一样,我将返回“你好”,或者如果我放入hijklm并将其移位7,我将返回“ aaaaaa”
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']
def decypher(text,shift):
# initialize ciphertext as blank string
dtext = ""
# loop through the length of the plaintext
for i in range(len(text)):
# get the ith letter from the plaintext
l = text[i]
# find the number position of the ith letter
n_alphabet = alphabet.index(l)
# find the number position of the cipher by adding the shift
c_num = (n_alphabet + shift ) % len(alphabet) - 6 - i
# find the cipher letter for the cipher number you computed
c_letter = alphabet[c_num]
# add the cipher letter to the ciphertext
dtext = dtext + c_letter
# return the computed ciphertext
return dtext
我需要解密此函数给我的原始单词:
def caesar(plaintext,shift):
# initialize ciphertext as blank string
ciphertext = ""
# loop through the length of the plaintext
for i in range(len(plaintext)):
# get the ith letter from the plaintext
letter = plaintext[i]
# find the number position of the ith letter
num_in_alphabet = alphabet.index(letter)
# find the number position of the cipher by adding the shift
cipher_num = (num_in_alphabet + shift + i) % len(alphabet)
# find the cipher letter for the cipher number you computed
cipher_letter = alphabet[cipher_num]
# add the cipher letter to the ciphertext
ciphertext = ciphertext + cipher_letter
# return the computed ciphertext
return ciphertext
答案 0 :(得分:1)
反转密码只需要继续移至达到一个完整周期的点(即其余字母):
def decypher(text,shift): return cypher(text,len(alphabet)-shift)
也,在您的代码中:
cipher_num = (num_in_alphabet + shift + i) % len(alphabet)
应该是
cipher_num = (num_in_alphabet + shift) % len(alphabet)