0

Although I found two other 'answered' questions on this topic, I'm trying to understand why this happens in python and have not found an answer yet other than 'that's just how python works'

In the below example, what I want is to initialize a new memo when canSum is called without a memo provided to it. However I notice when I call the function multiple times, the contents of memo seem to be pushed forward to future function calls:

def canSum(targetSum, nums, memo = {}):
    # memo base case
    if targetSum in memo:
        return memo[targetSum]

    # base case
    if targetSum == 0: return True
    if targetSum < 0: return False

    for num in nums:
        remainder = targetSum - num
        if canSum(remainder, nums, memo):
            memo[targetSum] = True
            return True

    memo[targetSum] = False
    return False

The solution I found on stackoverflow was pretty simple:

def canSum(targetSum, nums, memo = None):
    if memo == None:
        memo = {}

    .
    .
    .

Can anyone point me to some documentation of perhaps an explanation as to why this occurs in Python?

Chiken
  • 23
  • 6
  • 1
    Because the dictionary is created when you create the function, i.e. *once*, not when you call the function. – timgeb Jul 03 '22 at 16:02
  • I think that this might be because the function is referencing the default variable memo to initialize a new local variable memo in that time you called the function. With number values it works fine, but with things like list where a simple `=` operator only references, the behaviour you got is expected. It's the same reason why if `a=[]` and `b=a` then `b.append(1)`also changes a, instead of initializing b to be a.copy() – Game Developement Jul 03 '22 at 17:00

0 Answers0