I’m trying to learn a bit about dynamic programming and had a peice of code that creates a table of data, but I’m having a hard time figuring out what certain parts do.
Here’s the code:
from collections import defaultdict
data = [1, 2, 4]
sum = 10
# T[x, i] is True if 'x' can be solved
# by a linear combination of data[:i+1]
T = defaultdict(bool) # all values are False by default
T[0, 0] = True # base case
for i, x in enumerate(data): # i is index, x is data[i]
#print i, x
for s in range(sum + 1): #set the range of one higher than sum to include sum itself
#print s
for c in range(s / x + 1):
if T[s - c * x, i]:
T[s, i + 1] = True
I’m slowly starting to figure out how this code works but the second last line if T[s - c * x, i]: is a bit hard because I cannot replicate it fully in a terminal. When I type something simlair(using the values), it creates a matrix like [1,2] but how can that be true or false so it proceeds to the statement below?
If it helps, its part of some code that helps break down numbers. So I’m trying to figure out all the ways to break down 1,2,4 into 10. In this question, Can brute force algorithms scale?, I was suggested to create a dynamic table to reference.
Here’s the end result(which I’m having trouble interpreting the results):
{(7, 3): True, (1, 3): True, (9, 1): True, (3, 0): False, (8, 0): False, (2, 1): True, (6, 2): True, (5, 1): True, (0, 3): True, (10, 3): True, (7, 2): True, (4, 0): False, (1, 2): True, (9, 0): False, (3, 3): True, (8, 1): True, (6, 3): True, (5, 0): False, (2, 2): True, (10, 0): False, (4, 1): True, (1, 1): True, (3, 2): True, (0, 0): True, (8, 2): True, (7, 1): True, (9, 3): True, (6, 0): False, (2, 3): True, (10, 1): True, (4, 2): True, (1, 0): False, (5, 3): True, (0, 1): True, (8, 3): True, (7, 0): False, (9, 2): True, (6, 1): True, (3, 1): True, (2, 0): False, (4, 3): True, (5, 2): True, (0, 2): True, (10, 2): True}
Any clarification or suggestions of what to read up on to help understand would be great!
Thanks!
Not sure I fully undestand the question.
If the tuple
(x, y)exists in dictionaryT, thenT[x, y]will just returnTrueorFalseaccording to what has been saved to it. If(x, y)does not already exist, because ofT = defaultdict(bool), a non-existing key will causebool()to be called, which returnsFalse. You can replace theboolwith some custom function to make this clearerSince you are only assigning
True, the conditionif T[s - c * x, i]:is basically just checking whether(s-c*x, i)has been assigned manually or not. Normally we’ll use aset()for that.