简体   繁体   中英

IndexError: list index out of range in Python for function

I tried looking on this site but i can't find exactly what's going wrong with my program. It makes it all the way to 13 or the data_list[25] but then it spits out that IndexError message.

def rlEncode(n, z, data_list):
    while data_list[n] == data_list[n+1]:
        z = z + 1
        n = n + 1
    while data_list[n] != data_list[n+1]:
        return (n, z)

def unitTest( ):
    counter = 0
    n = 0
    z = 1
    data_list = [1,1,1,1,1,3,3,5,5,5,5,5,5,6,8,8,1,1,1,5,5,5,5,13,14, 14]
    compress_list = [ ]
    while counter < len(data_list):
        rlEncode(n, z, data_list)
        x, y = rlEncode(n, z, data_list)
        compress = [data_list[x], y]
        counter = counter + 1
        compress_list = compress_list + compress
        n = x+1
        z = 1
        continue
    print("list: ", data_list)
    print("compressed: ", compress_list)

In your rlEncode function, you are checking the while condition after incrementing n too high:

def rlEncode(n, z, data_list):
    while data_list[n] == data_list[n+1]:
        z = z + 1
        n = n + 1

The first time you check data_list[n] == data_list[n + 1] it's ok ... but then you do n = n + 1 , and go back to check the while condition. At this point, if n is 25, data_list[n + 1] will give you an index error, because data_list[25 + 1] does not exist.

You can check this by adding a print line like print(n, len(data_list)) just after n = n + 1 .

So either make sure you only iterate from 0 to 24, or make sure you do something like:

if n == len(data_list) - 1:
    break

You always have to keep the upper bounds of your arrays in mind when you are doing things like list[n + 1] anywhere in your algorithm.


Spoilers: Solution below:

In order to get your code working, I made two changes:

def rlEncode(n, z, data_list):
    # Make sure we don't overrun our list length:
    while n < len(data_list) - 1 and data_list[n] == data_list[n + 1]:
        z += 1
        n += 1
    return (n, z)

def unitTest( ):
    counter = 0
    n = 0
    z = 1
    data_list = [1,1,1,1,1,3,3,5,5,5,5,5,5,6,8,8,1,1,1,5,5,5,5,13,14,14]
    compress_list = []
    while n < len(data_list) - 1:  # Use n here, not counter
        rlEncode(n, z, data_list)
        x, y = rlEncode(n, z, data_list)
        compress = [data_list[x], y]
        counter = counter + 1
        compress_list = compress_list + compress
        n = x + 1
        z = 1
    print("list: ", data_list)
    print("compressed: ", compress_list)

unitTest()

('list: ', [1,1,1,1,1, 3,3, 5,5,5,5,5,5, 6, 8,8, 1,1,1, 5,5,5,5, 13, 14,14])
('compressed: ', [1,5, 3,2, 5,6, 6,1, 8,2, 1,3, 5,4, 13,1, 14,2])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM