“List index out of range” error

2019-08-28 12:34发布

问题:

I am writing a program in Python that will take a snippet of binary and encrypt it according to a key. If the snippet is shorter than the key, it has to take the last bit of the key, hence the double reverse. My problem comes when trying to add the last piece of the key to a blank list, where it gives me the "list index out of range" error. Code is as follows:

def OTP(msg,clave):
encList = []
encr = ''
clist = list(clave)
clist.reverse()
cutlist = []
mlist = list(msg)
mlist.reverse()
for i in range(len(msg)):
    cutlist.append(clist[i])
for i in mlist:
    for j in cutlist:
        if i == j:
            encList.append(0)
        if 1 != j:
            encList.append(1)
encList.reverse()
for i in encList:
    encr += str(encList[i])
return encr

clave = '000000010011010010001001000110110011001101010011100101010000101100111110000010100000011010010000101100000101100011010110100000100110001011001101101110110101000010000010100101000101101101010010001100001100100010111111111110010011101110010101110100111110000001101111110010000000101011000101111110100100101000110010111001100110011010100011011001101010011111100101'
msg = '01101000011010000110100001101000'

cript = OTP(msg,clave)
rev = OTP(cript,clave)
print(rev)

I am giving it the range of the length of the message, which should be within the range of the much longer key. As always, any help would be appreciated.

回答1:

The problem arose because by using a double for loop gave me a list with a number of items equal to the length of msg squared, because it considered each item in mlisttimes each item in cutlist.

This meant that when the function was called a second time (to decrypt the message and confirm the program worked), the msg argument was much longer than the clave argument, cre an error. To fix this, a single for loop with range(len(msg)) as a parameter can be used, and added 0 or 1 to encr depending on whether cutlist[i] == mlist[i].