0

I am having trouble understanding the following code although I tried it on pythontutor.

def fastFib(n, memo = {}):
if n == 0 or n == 1:
    return 1
try:
    return memo[n]
except KeyError:
    result = fastFib(n-1, memo) + fastFib(n-2, memo)
    memo[n] = result
    return result

My question is how come memo is not empty whenever it calls fastFib? When I tried it in pythontutor, there is only one memo and updated with new information. I thought that as fastFib(n, memo ={}) already specify the memo is empty, memo should be empty whenever it enters fastFib. What do I miss here?

Basically I think I am totally lost in this code. I really appreciate if you help me out understand this code.

Thank you.

  • You can try codeskulptor. Try the viz mode in it for debugging and going through the code. http://www.codeskulptor.org/viz/index.html – hshantanu Mar 06 '18 at 01:30
  • For reasons outlined in the duplicate link, `memo` is a global, mutable argument. It retains its value across calls. The try/except block says that if the computation result is already in `memo`, just return that value; otherwise, do the computation and add it to `memo`. – Prune Mar 06 '18 at 01:46

0 Answers0