I'm trying to learn some basic stuff in dynamic programming, but I got stuck in the following problem:
given as input an integer sum
and a list of positive integers numbers
, return the list made of the smallest amount of number belonging to numbers
that sum up to sum
.
Hope this is clear, I'll give you three examples:
if sum = 10
and numbers = (2, 3, 5)
should return [5, 5]
;
if sum = 0
and numbers = (2, 3, 5)
should return []
;
if sum = 10
and numbers = (3)
should return False
.
def bestsum(sum, numbers, memo={}):
if sum == 0:
return []
elif sum < 0:
return False
else:
if sum not in memo:
shortest_combination = False
for number in numbers:
remainder = sum - number
combination = bestsum(remainder, numbers)
if combination != False:
combination.append(number)
if shortest_combination == False or len(combination) < len(shortest_combination):
shortest_combination = combination
memo[sum] = shortest_combination
return memo[sum]
I do not put memo
as an input of my recursive call of bestsum
, since it worked with other dynamical programs I did before. Even if I add it, however, the script doesn't work, it update the memo
even when I do not do that explicitly. Adding a copy.copy
or actually inserting my memo
as input doesn't help. Maybe the problem is that I still miss how variables live in my memory when I call different and maybe recursively other functions.