I am writing a function that takes a target sum and an array of numbers as argument. The function should return a boolean ndicating if the target sum can be generated using the numbers from the array. I want to make the program more efficient, but when introducing a dictionary as a third argument, it stores information that are used when I run the function again. Here is the code:
def targetsum(TarS,lis, memo={}):
if TarS in memo:
return memo[TarS]
if TarS==0: return True
if TarS<0: return False
for num in lis:
remainder=TarS-num
if targetsum(remainder,lis,memo) == True:
memo[TarS]= True
return True
memo[TarS]= False
return False
print(targetsum(7,[2,4])) #false
print(targetsum(7,[2,3])) #true
The program returns false, false because it 'remembers' that 7 gives false from the first run. If I run I comment out one of the 'print' commands, everything works fine. How can I fix it? Thank you!