【发布时间】:2015-03-17 15:19:37
【问题描述】:
我正在尝试使用此代码将密文 "htrgti" 解密为纯文本。我不断收到 "wigvix" 这不是我应该收到的信息。
鉴于纯文本(应该是常用词或短语)和键,对于说 ciphertext 的每个位置,我将其替换为 plaintext,并且对于每个说 plaintext 的位置都相同:
def caesar(ciphertext, shift):
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"]
plaintext = ""
for i in range(len(ciphertext)):
letter = ciphertext[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
plain_num = (num_in_alphabet + shift) % len(alphabet)
# Find the plain letter for the cipher number you computed
plain_letter = alphabet[plain_num]
# Add the cipher letter to the plaintext
plaintext = plaintext + plain_letter
return plaintext
【问题讨论】:
-
想想用 dict 和 str.translate 来做这件事是多么容易!
-
如果您使用
N的移位进行编码,您将使用alphabet_len - N的移位进行解码。您目前使用什么班次值? -
另外,顺便说一句,字符串在 Python 中是可迭代的,因此无需将字母表显式设为列表。它也已作为
string.ascii_lowercase提供。 -
我使用的移位值是 15
-
这是教授的作业,让你每行都评论吗?
标签: python python-3.x