I am learning dynamic programming and a video i am watching shows a solution to a problem in JS like this:
I am trying to figure out how to write this solution in Python, i have made my recursive function like this:
def howSum(nums: List[int], target: int):
if target == 0:
return []
elif target < 0:
return None
for num in nums:
rem = target - num
res = howSum(nums, rem)
if res:
res.append(num)
return res
return None
print(howSum([2,3,5], 8))
But it my function returns None
instad of returning the array [2,2,2,2]
.
Is there something i am doing wrong to translate this function from JS to Python?
CodePudding user response:
Empty arrays are falsy in Python, so if res
should be if res is not None
(in order to match the corresponding condition in JS).