Which fix removes the bug?
def fib(n, memo={}):
if n <= 1:
return n
if n in memo:
return memo[n]
return fib(n - 1) + fib(n - 2)
- Change
n <= 1ton < 1in the base case - Change the default to
memo=Noneand init - Store result:
memo[n] = fib(n-1)+fib(n-2); return memo[n] - Remove the
if n in memocache check line
Results are read from memo but never written, so it never caches.
Play Problem Solving ▸