0

This is the code for returning a list of numbers that would add up to a given target number using the given list of elements. But it is returning the output from the elements of the previously run list as well. Here's the output when I run the below code: [1]: https://i.stack.imgur.com/rv1KY.png (This is generated by stackoverflow)

def howSum(target, numbers, memo = {}):
    if target in memo:
        return memo[target]
    if target == 0:
        return []
    if target < 0:
        return None
    
    for num in numbers:
        remainder = target - num
        remainderResult = howSum(remainder, numbers, memo)
        if remainderResult != None:
            memo[target] = [*remainderResult,num]
            return memo[target]
  
    memo[target] = None
    return None

    
print(howSum(7, [2,3]))
print(howSum(7, [5,3,4,7]))
print(howSum(7, [2,4]))
print(howSum(8, [2,3,5]))
print(howSum(300, [7,14]))

What is the mistake in this code that it is using previously given lists as well.

This is my first question here, please ignore if any mistakes. This code is python version of this problem from freecodecamp dynamic programming video in yt.

  • The problem is with your default value for `memo`. Look [here](https://stackoverflow.com/questions/26320899/why-is-the-empty-dictionary-a-dangerous-default-value-in-python). I suggest setting the default value to `None` and assign an empty dictionary in the body of the function. – Sajad Aug 10 '21 at 08:04

0 Answers0