Home > Mobile >  IndexError: list index out of range: When changing code format
IndexError: list index out of range: When changing code format

Time:10-14

The original code is:

def lucky_candies(a, k):
    l = [0]   (k-1) * [float('-inf')]
    for x in a:
        l = [max(l[(i-x) % k]   x, y) for i, y in enumerate(l)]
    return print(l[0])

lucky_candies([5000000,4000000,3000000,2000000,1000000], 9)

I tried to change it to something I can read:

def lucky_candies(a, k):
    l = [0]   (k-1) * [float('-inf')]
    for x in a:
        for i, y in enumerate(l):
            l = [max(l[(i-x) % k]   x, y)]
    return print(l[0])

lucky_candies([5000000,4000000,3000000,2000000,1000000], 9)

But this returns:

IndexError: list index out of range

CodePudding user response:

Old code gives list l of length k, while new code immediately makes one-element list l, so handling with indices>0 becomes illegal

Append max(l[(i-x) % k] x, y) to new list

CodePudding user response:

Create a new list (called result) for every iteration of a to hold the new l. As an aside, what is the reason for using return print(l[0])? You can just return.

Try the following:

def lucky_candies(a, k):
    l = [0]   (k-1) * [float('-inf')]
    for x in a:
        result = list()
        for i, y in enumerate(l):
            result.append(max(l[(i-x) % k]   x, y))
        l = result
    return l[0]

>>> lucky_candies([5000000,4000000,3000000,2000000,1000000], 9)
9000000
  • Related