-3
N = 3
sum1 = 4
rows, cols = (N+1, sum1+1)
dp = [[-1 for i in range(rows)] for j in range(cols)]
for i in range(0, cols):
    dp[0][i] = False
    
for i in range(0, rows):
    dp[i][0] = True

I'm not sure why I'd get a list index out of range exception for this code, the only time it doesnt show an error is when I edit the line "dp[0][i] to dp[0][i-1]" The aim is to have a matrix dp size 3*4 with the first column entirely True and the row 0 to be entirely False except at 0,0 where it is True

Rah Maha
  • 3
  • 2
  • 3
    Why do you think you can index to `cols` in a `list` of `len(cols)`? Legal `list` indices go from `0` to `len(thelist) - 1`, and your `+ 1` in each `range` means you go one beyond that. – ShadowRanger Oct 15 '21 at 05:18
  • "I'm not sure why I'd get a list index out of range exception" In your own words, exactly what values of `i` do you think make sense to use in `dp[0][i] = False`? (List all of them, and don't list anything else.) In your own words, what values of `i` do you think will be set by `for i in range(0, cols+1):`? (List all of them, and don't list anything else.) Now, *test* what you thought was the case. – Karl Knechtel Oct 15 '21 at 05:41
  • @ShadowRanger Thank you for this, I just noticed I posted the wrong code, could you please look at the edit and let me know what could be the reason? Thanks! – Rah Maha Oct 15 '21 at 06:56

1 Answers1

0

You are creating the following matrix:

[[-1, -1, -1, -1],
 [-1, -1, -1, -1],
 [-1, -1, -1, -1],
 [-1, -1, -1, -1],
 [-1, -1, -1, -1]]

So when you try to iterate through cols+1 (6 in this case) you overflowing the four columns total that you have created.

Plus, if you want to create a 3*4 matrix, why do you increase these:

rows,cols=(N+1,sum1+1)

In any case, you want cols-1 and rows-1. But as mentioned by @Rah Maha below, rows+1 works, so you are inverting the axis.

N = 3
sum1 = 4
rows, cols = (N+1, sum1+1) # still should not be +1 if you want a 3x4 matrix
# changed cols and rows position so it will be what you want
dp = [[-1 for i in range(cols)] for j in range(rows)]
for i in range(0, cols):
    dp[0][i] = False
    
for i in range(0, rows):
    dp[i][0] = True
Hugofac
  • 53
  • 8
  • "you want cols-1 and rows-1" -- hmm, actually, `rows-1` doesn't work, but `rows+1` does. It looks like OP got the axes mixed up somewhere. – wjandrea Oct 15 '21 at 06:04
  • Thank you so much for this, I just noticed I posted the wrong code actually, please could you look at the edits and let me know what could be the problem? – Rah Maha Oct 15 '21 at 06:55