Home > Software engineering >  I have an error " list index out of range" that I can't solve
I have an error " list index out of range" that I can't solve

Time:11-08

I am working on a problem from code wars. It is "Delete occurrences of an element if it occurs more than n times". The instructions are Given a list lst and a number N, create a new list that contains each number of lst at most N times without reordering. For example if N = 2, and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2], drop the next [1,2] since this would lead to 1 and 2 being in the result 3 times, and then take 3, which leads to [1,2,3,1,2,3].

Example: delete_nth ([1,1,1,1],2) # return [1,1] delete_nth ([20,37,20,21],1) # return [20,37,21]

The issue is that when I run this in code wars it comes back with the error.

Traceback (most recent call last):
  File "tests.py", line 30, in <module>
    do_test()
  File "tests.py", line 9, in do_test
    test.assert_equals(delete_nth([], 5), [], "From list [],5 you get")
  File "/workspace/default/solution.py", line 6, in delete_nth
    if o.count(o[x]) > max_e:
IndexError: list index out of range

But everything is fine and I get zero errors when I run it in VSC. I know what the error is telling me but I just can't understand or see how that is.

def delete_nth(order,max_e):
    o = order[::-1]
    x = 0

    while x != len(o) 1:
        if o.count(o[x]) > max_e:
            o.remove(o[x])
        x  = 1
        if x >= len(o):
            return(o[::-1])

    return(o[::-1])

CodePudding user response:

Try putting

if order == []:
    return []

before the while loop (of course at the same indentation level with while).

The error happens when you put [] as the first parameter, as the error message indicates. In that chase o in your code is an empty list, so in the while loop o[x] cannot be evaluated. The if above will deal with this pathological case.

  • Related