0

I have the following code, that checks if the target sum can be achieved using the list of numbers given. I am trying to memoize the function by storing the values in a dictionary.

def how_Sum(target_Sum, numbers, memo={}):
    if target_Sum in memo:
        return memo[target_Sum]
    if target_Sum == 0:
        return []
    if target_Sum < 0:
        return None

    for num in numbers:
        remainder = target_Sum - num
        remainder_Result = how_Sum(remainder, numbers, memo)
        if remainder_Result != None:
            memo[target_Sum] = remainder_Result + [num]
            print(memo)
            return memo[target_Sum]

    memo[target_Sum] = None
    return None

Now when I call the function like this, I get the following result which is correct. print(how_Sum(7, [2, 3])) gets me,

{1: None, 3: [3]}
{1: None, 3: [3], 5: [3, 2]}
{1: None, 3: [3], 5: [3, 2], 7: [3, 2, 2]}
[3, 2, 2]

And when I call this function, print(how_Sum(7, [5, 3, 4]) I get the following which is also correct,

{2: None, 1: None, 4: [4]}
{2: None, 1: None, 4: [4], 7: [4, 3]}
[4, 3]

Now when I run both of them together,

print(how_Sum(7, [2, 3]))
print(how_Sum(7, [5, 3, 4]))

I get this result,

{1: None, 3: [3]}
{1: None, 3: [3], 5: [3, 2]}
{1: None, 3: [3], 5: [3, 2], 7: [3, 2, 2]}
[3, 2, 2]
[3, 2, 2]

Now from my understanding, the dictionary gets created for the first function and doesn't get cleared for the second call. Can someone explain me why this behaves this way, and how to rectify this?

  • `Special cases aren't special enough`. If you try always using `[]` rather than `None` to indicate "no possible solutions", you should find that you can simplify the logic and remove conditionals. – Karl Knechtel Apr 09 '21 at 02:15
  • Also, if you want to memoize results, you should [use the built-in standard library functionality for that](https://docs.python.org/3/library/functools.html#functools.cache). – Karl Knechtel Apr 09 '21 at 02:17
  • Anyway, it works that way because that's how the language is defined. The linked duplicate gives more detail. It works the same way for dicts as for lists, or for any other mutable default argument. – Karl Knechtel Apr 09 '21 at 02:18

0 Answers0