I was writing following algorithm for howsum problem where if it is possible to calculate the target value from the given array values. if possible, I return the combination that gives the target sum, if not I return None.
The following recursive program works as expected, however , if I am to return ans.append(value)
along with return
statement in the same line, program always return None
. I spent a lot of time to figure out the reason for this behavior. any help is highly appreciated.
working code
def how_sum(targetSum, arr):
if targetSum == 0:
return []
elif targetSum < 0:
return None
for index, value in enumerate(arr):
ans = how_sum(targetSum - value, arr)
if ans is not None:
ans.append(value)
return ans
return None
result = how_sum(7, [7])
print(result)
code which always return None
, only difference is , I am returning ans.append(value)
in the same line with return
statement
def how_sum(targetSum, arr):
if targetSum == 0:
return []
elif targetSum < 0:
return None
for index, value in enumerate(arr):
ans = how_sum(targetSum - value, arr)
if ans is not None:
return ans.append(value)
return None
result = how_sum(7, [7])
print(result)