I wrote a simple recursive program to get the Nth Fibonacci number with a cache to speed it up.
def fibonacci(n, cache={0:0, 1:1}):
if n-1 not in cache:
cache[n-1] = fibonacci(n-1)
return cache[n-1] + cache[n-2]
The problem with that code is that I forgot to pass the cache variable into the recursive call, so I wouldn't expect it to work, since I can't access cache[n-2] once n > 3 -- however, it does work just the same as the the following correct example:
def fibonacci(n, cache={0:0, 1:1}):
if n-1 not in cache:
cache[n-1] = fibonacci(n-1, cache)
return cache[n-1] + cache[n-2]
Can someone explain to me why it seems like cache is being passed into the recursive call in the first snippet?