1
def solution(progresses, speeds):
    answer = []
    while len(progresses) != 0:
        count = 0
        for i in range(len(progresses)):
            if progresses[i] < 100:
                progresses[i] += speeds[i]
        while (progresses[0] >= 100) and (len(progresses) != 0):
            print("pop: ", progresses.pop(0))
            speeds.pop(0)
            count += 1
        if count != 0:
            answer.append(count)

    return answer


solution([93, 30, 55], [1, 30, 5])

my python terminal show me an error like this.

    while (progresses[0] >= 100) and (len(progresses) != 0):
IndexError: list index out of range

i dont know why this error comes up..... help me

1
  • 3
    Don't modify lists while you're iterating over them. You're poping everything off the list, eventually there's nothing left and then you have an index error at 0 because the list is empty. Commented Apr 6, 2022 at 13:53

2 Answers 2

1

As mentioned in other comments you should avoid modifying the list which is used in the while or for loop checks.


If you want to understand why your code is failing. The problem is this line:

while (progresses[0] >= 100) and (len(progresses) != 0):

You are accessing element zero (progresses[0]) but the list is empty. If you swap the two checks, it works fine (because if the first check already returns false the second check is not performed at all).

while (len(progresses) != 0 and progresses[0] >= 100):
Sign up to request clarification or add additional context in comments.

Comments

1

Agree with the comment. If you want, you can do import copy and copy_of_speeds = copy.deepcopy(speeds), which will make a copy of the list that isn't tied to it, which you could loop over instead.

Your code also has the bug in the code, where

while progresses[0] >= 100:
            progresses.pop(0)

could potentially have progresses pop all the way to an empty list, and then progresses[0] hits that index error!. So if you do

while len(progresses) > 0 && progresses[0] >= 100 instead, which won't hit that issue.

1 Comment

In the future, why not try printing information in your code as the code is running, which will mean that you can find out what's going on

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.