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?