0

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
8
  • 2
    You do not need to use ; semicolons in python. They only add noise. Commented Sep 21, 2012 at 15:35
  • Given that you've already used the expression coins[j] in the line above, that can't be it. Try printing the value of that expression. Commented Sep 21, 2012 at 15:37
  • 2
    Why are you importing array? You're not using any of the functions in that module. Commented Sep 21, 2012 at 15:39
  • @MartijnPieters I write basically in C++, so I have got used to add ; Commented Sep 21, 2012 at 15:40
  • I think you got confused about arrays as well then. In your code you are using python lists, which is fine, but don't call them arrays, nor do you need to import the array module. Commented Sep 21, 2012 at 15:42

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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?

Comments

0

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

Comments

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.