I just learned about memoization for optimizing recursive functions. The solution for memoizing a Fibonacci function was provided as:
def fib_memo(n, memo={}):
if n in memo : return memo[n]
if n in [1,2]: return 1
memo[n] = fib_memo(n-1, memo) + fib_memo(n-2, memo)
return memo[n]
print(fib_memo(50))
>>> 12586269025
However, I have found that the following variation (which does not pass memo
in the recursive calls) also works as expected, but I am unable to explain how/why:
def alt_memo(n, memo={}):
if n in memo : return memo[n]
if n in [1,2]: return 1
memo[n] = alt_memo(n-1) + alt_memo(n-2)
return memo[n]
print(alt_memo(50))
>>> 12586269025
When I run alt_memo(n)
, is my compiler optimizing the code behind the scenes and adding memo
in the recursive calls, or is it in fact not necessary to include memo
in the recursive calls?
If not necessary, how is it that the recursive calls are receiving/passing-along the memo
object (being as that the function initially sets the memo
parameter to an empty dictionary, when otherwise unspecified)?