0

Here is the code: `

def canSum(targetSum, numbers, m = {}):
    if targetSum in m:
        return m[targetSum]
    
    if targetSum == 0:
        return True
    
    if targetSum < 0:
        return False

    for number in numbers:
        remainder = targetSum - number
        if canSum(remainder, numbers, m):
            m[targetSum] = True
            return True

    m[targetSum] = False
    return False

print(f'Answer: {canSum(7, [2, 3])}') # true
print(f'Answer: {canSum(7, [5, 3, 4, 7])}') # true
print(f'Answer: {canSum(7, [2, 4])}') # false 
print(f'Answer: {canSum(8, [2, 3, 5])}') # true
print(f'Answer: {canSum(300, [7, 14])}') # false

`

The problem is that when I remove the default value in function arguments, and pass the empty dictionary when I am calling the function, all works fine. But if I don't want to pass the empty dictionary when I am calling the function, I just want to pass the default value.

In JavaScript it works fine, however in Python I don't know why it is happening like that. Can someone explain me, thanks!

In JavaScript it works fine, however in Python I don't know why it is happening like that. Can someone explain me, thanks!

  • 2
    You are using a **mutable** default value. More info [here](https://florimond.dev/en/posts/2018/08/python-mutable-defaults-are-the-source-of-all-evil/) – Marat Oct 26 '22 at 17:59
  • Read [this article](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) for tips on debugging your code. – Code-Apprentice Oct 26 '22 at 17:59
  • 1
    default values are evaluated once when the function is defined. – juanpa.arrivillaga Oct 26 '22 at 17:59
  • You could define the default with `m=None` and then do `if m is None: m = {}` in the first line of the function. With this approach you create a new dictionary for every call if you don't provide the parameter `m`. – Matthias Oct 26 '22 at 18:03

0 Answers0