Fibonacci without the waste: remember answers in a dict (top down), or fill a table from the bottom up.
Python · intermediate · 9 min · 53 steps · free
def fib_memo(n, memo):
if n in memo:
return memo[n]
if n <= 1:
return n
memo[n] = fib_memo(n - 1, memo) + fib_memo(n - 2, memo)
return memo[n]
def fib_table(n):
table = [0, 1]
for i in range(2, n + 1):
table.append(table[i - 1] + table[i - 2])
return table[n]
print(fib_memo(5, {}), fib_table(5))fib_memo(). Its body does not run yet: it runs each time the function is called.fib_table(). Its body does not run yet: it runs each time the function is called.fib_memo(), with n = 5 and memo = {}. It gets its own names.n in memo is false, so the block under it is skipped.n <= 1 is false, so the block under it is skipped.n in memo is false, so the block under it is skipped.n <= 1 is false, so the block under it is skipped.fib_memo() #3, with n = 3 and memo = {}. It gets its own names.n in memo is false, so the block under it is skipped.n <= 1 is false, so the block under it is skipped.fib_memo() #4, with n = 2 and memo = {}. It gets its own names.n in memo is false, so the block under it is skipped.n <= 1 is false, so the block under it is skipped.fib_memo() #5, with n = 1 and memo = {}. It gets its own names.n in memo is false, so the block under it is skipped.n <= 1 is true, so the block under it runs.n.fib_memo() #5 has finished. Python calls fib_memo() #5, with n = 0 and memo = {}. It gets its own names.n in memo is false, so the block under it is skipped.n <= 1 is true, so the block under it runs.n.memo[n].fib_memo() #4 has finished. Python calls fib_memo() #4, with n = 1 and memo = {2: 1}. It gets its own names.n in memo is false, so the block under it is skipped.n <= 1 is true, so the block under it runs.n.fib_memo() #4 has finished, so its names are gone. A new key 3 with the value 2 is added to the dict that memo points to.memo[n].fib_memo() #3 has finished. Python calls fib_memo() #3, with n = 2 and memo = {2: 1, 3: 2}. It gets its own names.memo[n].fib_memo() #3 has finished, so its names are gone. A new key 4 with the value 3 is added to the dict that memo points to.memo[n].fib_memo() #2 has finished. Python calls fib_memo() #2, with n = 3 and memo = {2: 1, 3: 2, 4: 3}. It gets its own names.n in memo is true, so the block under it runs.memo[n].fib_memo() #2 has finished, so its names are gone. A new key 5 with the value 5 is added to the dict that memo points to.memo[n].fib_table(), with n = 5. It gets its own names. fib_memo() has finished, so its names are gone.i is created with the value 2.i changes from 2 to 3.table points to.i changes from 3 to 4.table points to.i changes from 4 to 5.table points to.for i in range(2, n + 1).table[n].Answer: 1.6 million calls
Answer: The table
← Backtracking: All Subsets · Dynamic Programming: Coin Change →