【发布时间】:2016-05-13 03:17:54
【问题描述】:
我开始编写代码来执行 Vigenere 密码加密。首先,我想制作钥匙。密钥需要一遍又一遍地重复,直到它与要加密的消息的长度相匹配,所以我创建了一个可以为我执行此操作的函数:
def makekey(key, message):
finalkey = []
print(message) # to see if the key fits under the message correctly
key = list(key)
while len(finalkey) < len(message): # while the key is shorter than the message
for i in range(0, len(key)): # iterate through characters in the key
finalkey.append(key[i]) # append the characters in the processed key list
if len(finalkey) > len(message): # if the final key is still bigger than the message
difference = len(finalkey) - len(message) # finds the difference between the two
del key[-difference] # removes the difference
return ''.join(finalkey) # joins the final key into a string
print(makekey("LOVE", "Python")) # calling the function
输出应如下所示:
Python
LOVELO
但是程序只是给了我一个超出范围的索引错误,我不知道发生了什么!
错误信息:
Traceback (most recent call last):
File "test.py", line 14, in <module>
print(makekey("LOVE", "Python")) # calling the function
File "test.py", line 8, in makekey
finalkey.append(key[i]) # append the characters in the processed key list
IndexError: list index out of range
【问题讨论】:
-
有一个更简单的方法使用cycle
-
itertools -> 循环。