Q. Write a function "canSum(target_sum, numbers)" that takes in a target_sum and an array of numbers as arguments. The function should return a boolean indicating whether or not it is possible to generate the target_sum using numbers from the array.
You may use an element of the array as many times as needed. You may assume that all numbers are non-negative.
Eg: canSum(7, [1, 2, 5, 3, 7]) --> true
Eg: canSum(7, [2, 4, 9, 6]) --> false
Here is my solution, but it only works when i remove memoization.
def canSum(target_sum, numbers, memo={}):
if target_sum in memo:
return memo[target_sum]
if target_sum == 0:
return True
if target_sum < 0:
return False
for num in numbers:
if canSum(target_sum - num, numbers, memo) == True:
memo[target_sum] = True # removing this gives expected output.
return True
memo[target_sum] = False # removing this gives expected output.
return False
if __name__ == "__main__":
print(canSum(7, [2, 5, 7])) # Output: True
print(canSum(7, [2, 4])) # Output: True (while it should be false).
After removing memo, now it works correctly. Please help, I cant find why is this happening.
for num in numbers:
if canSum(target_sum - num, numbers, memo) == True:
return True
return False
# Now it works fine.