Rontogiannis Aristofanis
Rontogiannis Aristofanis

Reputation: 9063

Python list dimension size error

Consider the following code in python:

def main():
    n = input( )
    s = input( )

    coins = [ 0 ]*n
    dp = [ 0 ]*( s+1 )

    print coins
    print dp

    for i in range( n ) :
        coins[ i ] = input( )

    dp[ 0 ]=0
    dp[ 1 ]=1

    for i in range( 2, s+1 ) :
        min_val = 999999
        for j in range( 0, n ) :
            if i-coins[ j ] > 0 :
                if dp[ i-coins[ j ] ] + 1 < min_val :
                    min_val = dp[ i-coins[ j ] ] + 1


    print coins
    print dp

    print coins[ s ]

if __name__ == "__main__" :
    main()

When I compile and run this program, I get the following runtime error:

File "test.py", line 33, in <module>
  main();
File "test.py", line 30 in main
  if dp[ i-coins[ j ] ] + 1 < min_val :

IndexError: list index out of range

What's wrong with it?

Input:

5 10
1 3 5 7 9

Upvotes: 0

Views: 1625

Answers (3)

Marcus
Marcus

Reputation: 6839

try to use

coins = [ 0 ]*n
dp = [ 0 ]*( s+1 )

to init the array.

I got an total different error on my machine:

  File "ttt.py", line 31, in <module>
    main()
  File "ttt.py", line 21, in main
    if dp[ i-coins[ j ] ] + 1 < min_val :
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

and print dp[s] rather than print coins[s] at the last line.

Upvotes: 1

fatrock92
fatrock92

Reputation: 837

dp is s+1 length but your for loop goes to n. If s+1 > n then this would work. But in this case I think your s+1 < n.

dp = [ None ]*( s+1 ); # dp is s+1 in length.

for j in range( 0, n ) # loop goes to n.

list index out of range means that s+1 < n

Upvotes: 0

ecatmur
ecatmur

Reputation: 157344

We know (from the previous line if) that i-coins[ j ] > 0, so it must be greater than or equal to len(dp), which is s + 1. i is less than s+1, so coins[ j ] is a negative number.

Did you enter a negative number for one of the coins?

Upvotes: 1

Related Questions