Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I got error saying IndexError: list index out of range. how do I fix this?

   res = [3, 1, 1, 5, 2, 4, 2, 4, 2, 4, 3, 1, 1, 5, 3]      

   while not i>(len(res)-1):
        if res[i]==res[i+1]:
            answer+=2
            i+=2
        else:
            i+=1

The variable "answer" is supposed to count duplicated numbers that are placed next to each other. For some reason, I get the error saying IndexError: list index out of range. How do I fix this?

like image 388
Sung Yeon Park Avatar asked Nov 03 '25 06:11

Sung Yeon Park


2 Answers

Let's start off by simplifying the code a bit. The condition

not i > (len(res) - 1)

can be converted to

i <= (len(res) - 1)

which can be further converted to

i < len(res)

This means that i will always be less than the length of res, which makes it a valid index. However, within the body of the while, on this line:

if res[i]==res[i+1]:
    ...

we indexed res with i + 1, which for the last possible value of i will be an invalid index (i + 1 will be equal to len(res)). We have to ensure that not only i is less than len(res), but also that i + 1 is less than len(res), giving us this fixed version of the code:

while i + 1 < len(res):
    if res[i] == res[i + 1]:
        answer += 2
        i += 2
    else:
        i += 1

Running this code on your example res gives an answer of 4, which looks right.

like image 124
Mario Ishac Avatar answered Nov 04 '25 20:11

Mario Ishac


How about giving it this approach?

res = [3, 1, 1, 5, 2, 4, 2, 4, 2, 4, 3, 1, 1, 5, 3]
answer = 0
start = 0
while start < len(res):
    if start + 1 < len(res):
        if res[start] == res[start + 1]:
            answer += 1
            start += 2
        else:
            start += 1
    else:
        start += 1
print(answer)
like image 43
Albert Alberto Avatar answered Nov 04 '25 18:11

Albert Alberto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!