I'm practicing Dynamic Programming and I'm struggling with debugging my code. The idea is to find if a sum is possible given a list of numbers. Here's my code:
a = [2,3,7,8,10] sum = 11 b = list(range(1, sum+1)) m = [[False for z in range(len(b))] for i in range(len(a))] for i, x in enumerate(b): for j, y in enumerate(a): if x==y: m[j][i]=True elif y<x: m[j][i] = m[j-1][i] else: m[j][i] = m[j-1][i] or m[j-i][y-x] for i, n in enumerate(m): print(a[i], n) And here is the output:
2 [False, True, False, False, False, False, False, False, False, False, False] 3 [False, True, True, False, False, False, False, False, False, False, False] 7 [False, True, True, False, True, True, True, False, False, False, False] 8 [False, True, True, False, True, True, True, True, False, False, False] 10 [False, True, True, False, True, True, True, True, True, True, False] As I understand it, in my else statement, the algorithm is supposed to go up 1 row and then look at the difference of x and y and check if that slot is possible. So for instance in the most obvious case, the last element in the last row. That would be 10(y)-11(x) which should go all the way back to index 1 on the row above it, which as we know it's True. Not entirely sure what I'm doing wrong, any help in understanding this would be greatly appreciated.