0

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)
KItis
  • 5,476
  • 19
  • 64
  • 112
  • 1
    `ans.append(value)` will append to the list and return None. It is like `return print('something')`. Thats why you are getting `None` as a result – Joe Ferndz Mar 30 '21 at 05:10
  • See the links [1](https://stackoverflow.com/questions/16641119/why-does-append-always-return-none-in-python), [2](https://stackoverflow.com/questions/11205254/why-dont-list-operations-return-the-resulting-list) – Joe Ferndz Mar 30 '21 at 05:11

0 Answers0