0

I was studying dynamic programming and I came across this weird problem where a function call is affected by a previous call to the function with different parameters

def bestSum(target, numbers,memo={} ):
    if target in memo:
        return memo[target]
    if target == 0:
        return []
    if target < 0:
        return None
    shortest = None
    for num in numbers:
        remainder = target - num
        result = bestSum(remainder, numbers,memo)
        if(result is not None):
            result.append(num)
            combination = result
            if shortest is None or len(result) < len(shortest):
                shortest = combination
    memo[target] = shortest
    return shortest
#print (bestSum(300,[8,14]))
#print (bestSum(8,[2,3,5]))
print (bestSum(10, [2,5,25]))

the above code executes perfectly when running the last print statement and prints the best possible array [5,5], but when I try to run the last two lines it gets affected by the above line which outputs [3,5], and prints [5,3,3,2], where could possible be the bottle neck here and is there any "flush" operation that needs to be done?

Hitham
  • 23
  • 7
  • I believe that this is a dupe of [this](https://stackoverflow.com/questions/1367883/methods-default-parameter-values-are-evaluated-once) question. Long story short, `memo={}` creates one object when the function definition is evaluated, and that single dictionary is shared across all calls. To "flush" it, you'd need to do something like call `memo.clear()` from within the function. – Carcigenicate Mar 08 '21 at 23:31

1 Answers1

0

What you need to do is change the start of your function to the following:

def bestSum(target, numbers,memo=None ):
    if memo is None:
        memo = {}

This keeps memo from accidentally being shared between function calls when it was not explicitly passed.

btilly
  • 43,296
  • 3
  • 59
  • 88