Python重复列表索引超出范围

时间:2016-03-01 13:59:15

标签: python python-3.x

所以我正在尝试为我的GCSE工作做一个vigenere密码(或类似的东西)。然而,我遇到的一个问题是我的列表索引总是超出范围,但我所拥有的代码与之前的代码完全相同,并且没有错误。这是我的代码:

#Encrypting
def encrypt():
     #>Creating initial variables
     plainText = str(input('Input your plain text \n --> ')).upper()
     key = str(input('Input your key. Make sure it is as long as your plain text. \n --> ')).upper()

    #>Looping key
    if len(key) < len(plainText):
        key = len(plainText)*key
    else:
        key = key

    #>Creating lists for ASCII values of each letter
    plainAscii=[ord(i) for i in plainText]
    keyAscii=[ord(k) for k in key]

    #>Shortening the keyAscii list
    while len(keyAscii) != len(plainAscii):
        keyAscii.pop(len(keyAscii) - 1)

    #>Adding the values together and putting them into a new list
    cipherAscii=[]
    x = 0
    while x < len(key):
        item = (plainAscii[x] + keyAscii[x]) - 75
        cipherAscii.append(item)
        x = x + 1

    #>Making sure all numbers are within the 65 - 90 window

    newCipher=[]
    for c in cipherAscii:
        if c > 90:
            c = c - 26
            newCipher.append(c)
        elif c < 65:
            c = c + 26
            newCipher.append(c)
        else:
            newCipher.append(c)

    #>Converting the ASCII back into regular letters
    cipherText=[chr(i) for i in newCipher]

    #>Printing the cipher text
    for i in cipherText:
        print (i, end="")

我的代码错了吗?请尽快帮忙,因为我没有很多时间。

2 个答案:

答案 0 :(得分:1)

问题似乎是这一部分:

key

通过将len(plainText)x相乘,您可以重复该键。这会在您的循环中导致问题,len(plainText)可能会比while x < len(key): item = (plainAscii[x] + keyAscii[x]) - 75

大得多
if len(key) < len(plainText):
    key = key[:len(plainText)]

相反,您希望将密钥修剪为与纯文本相同的长度。

>>> 3 * "abcde"
'abcdeabcdeabcde'
>>> "abcde"[:3]
'abc'

简单演示:

    Error creating bean with name 'jobOperator' defined in class path resource [atlentic-Spring-Batch-common.xml]: Cannot resolve reference to bean 'jobExplorer' while setting bean property 'jobExplorer' [...]
Error creating bean with name 'connex' defined in class path resource [batch-calendar-context.xml]: Error setting property values;[...] Bean property 'dataSource' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

答案 1 :(得分:0)

我刚注意到我之前的回答是错误的,所以我发布了一个新答案......

问题不在于你填充密钥的方式,它更简单:你填充key 很多,然后创建密钥的ASCII版本,{{ 1}},将版本的版本修剪为正确的长度,然后将 loop 修剪为更长keyAscii的每个角色。

要解决此问题,您所要做的就是将循环条件更改为

key
转换为ASCII之前

或将while x < len(keyAscii): 修剪为正确的长度

key

此外,您不需要填充密钥:如另一个(现已删除)答案中所述,您只需重复密钥# trim after padding if len(key) > len(plainText): key = key[:len(plainText)] 次,即

ceil(len(text)/len(key))

此外,使用key = key * int(math.ceil(len(text)/len(key))) itertools.cycle可以让您的功能更加简单:

zip