I am trying to understand memoization, and this fib function seems to give me the correct answers. My question is how and where the dictionary is stored. Why does it give me fib(7) and fib(8) immediately? What is the namespace of d? Is it treated like a global variable or sort of something? My codes and what the codes gave me are here. Thank you.
def fib(n, d = {}):
if n in d:
return d[n]
elif n < 3:
return 1
else:
d[n] = fib(n - 1, d) + fib(n - 2, d)
print(f"n: {n}")
print(f"d: {d}")
return d[n]
print("fib(6):", fib(6))
print("fib(7):", fib(7))
print("fib(8):", fib(8))
--------------------------------------------------------------------------------------------
n: 3
d: {3: 2}
n: 4
d: {3: 2, 4: 3}
n: 5
d: {3: 2, 4: 3, 5: 5}
n: 6
d: {3: 2, 4: 3, 5: 5, 6: 8}
fib(6): 8
n: 7
d: {3: 2, 4: 3, 5: 5, 6: 8, 7: 13}
fib(7): 13
n: 8
d: {3: 2, 4: 3, 5: 5, 6: 8, 7: 13, 8: 21}
fib(8): 21