fork download
  1. from collections import defaultdict
  2.  
  3. data = [1, 2, 4]
  4. target_sum = 10
  5.  
  6. # T[x, i] is True if 'x' can be solved
  7. # by a linear combination of data[:i+1]
  8. T = defaultdict(bool) # all values are False by default
  9. T[0, 0] = True # base case
  10.  
  11.  
  12. for i, x in enumerate(data): # i is index, x is data[i]
  13. for s in range(target_sum + 1): #set the range of one higher than sum to include sum itself
  14. for c in range(s // x + 1):
  15. if T[s - c * x, i]:
  16. T[s, i+1] = True
  17.  
  18. coeff = [0]*len(data)
  19.  
  20. def RecursivelyListAllThatWork(k, sum_): # Using last k variables, make sum
  21. # /* Base case: If we've assigned all the variables correctly, list this
  22. # * solution.
  23. # */
  24. if k == 0:
  25. # print what we have so far
  26. terms = list(zip(coeff, data))
  27. print("%s = %s" % (' + '.join("%2s*%s" % t for t in terms), sum(t[0]*t[1] for t in terms)))
  28. return
  29. x_k = data[k-1]
  30. # /* Recursive step: Try all coefficients, but only if they work. */
  31. for c in range(sum_ // x_k + 1):
  32. if T[sum_ - c * x_k, k - 1]:
  33. # mark the coefficient of x_k to be c
  34. coeff[k-1] = c
  35. RecursivelyListAllThatWork(k - 1, sum_ - c * x_k)
  36. # unmark the coefficient of x_k
  37. coeff[k-1] = 0
  38.  
  39. RecursivelyListAllThatWork(len(data), target_sum)
Success #stdin #stdout 0.03s 6412KB
stdin
Standard input is empty
stdout
10*1 +  0*2 +  0*4 = 10
 8*1 +  1*2 +  0*4 = 10
 6*1 +  2*2 +  0*4 = 10
 4*1 +  3*2 +  0*4 = 10
 2*1 +  4*2 +  0*4 = 10
 0*1 +  5*2 +  0*4 = 10
 6*1 +  0*2 +  1*4 = 10
 4*1 +  1*2 +  1*4 = 10
 2*1 +  2*2 +  1*4 = 10
 0*1 +  3*2 +  1*4 = 10
 2*1 +  0*2 +  2*4 = 10
 0*1 +  1*2 +  2*4 = 10