Why there is no difference between passing in the memo dict and not passing it?

Question:

So I have this memoized algorithm for the Fibonacci sequence and I faced something a little strange, there is no impact on the time complexity if I pass the memo dict in line 4, or if I don’t, I want to understand why? isn’t memo supposed to be empty in the later recursive calls?

here’s the code without passing memo in line 4:

def fib(n , memo = {}):
    if(n<=2): return 1
    if(n in memo): return memo[n]
    memo[n] = fib(n-1) + fib(n-2)
    return memo[n]

and here it is when I pass it:

def fib(n , memo = {}):
    if(n<=2): return 1
    if(n in memo): return memo[n]
    memo[n] = fib(n-1 , memo) + fib(n-2 , memo)
    return memo[n]

you can try it there is no difference in the time complexity.

Asked By: Haidara

||

Answers:

memo will be initialized to the default value (empty dict) exactly once. After that, the default value memo is the previously initiated instance, so inside the function, you are always modifying the same instance of the dict.

Check this passage from the python tutorial:

Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls: […]

Answered By: treuss