Python 3D Academyবাংলা

Recursion trees and their cost: memoization

🌍 In real life. A maths test asks for 37 × 24 in question 2, and again inside questions 5 and 9. One student works it out from scratch all three times. Another works it out once and writes the answer in the margin; the next time, a glance at the margin is enough. Same answers, a third of the work.

Plain recursion is the first student. When a function calls itself more than once, the calls branch into a tree, and the same question can come up again and again in different branches. This lesson counts exactly how much that costs, and fixes it with a margin: a memo.

The idea in one sentence: draw every call as a node under the call that made it; the total work is the number of nodes, and when the same call appears more than once, remembering its first answer (memoization) removes every repeat.

Its words:

  • recursion tree: the calls drawn as a tree, the first call at the top
  • overlapping subproblems: the same smaller problem asked more than once
  • memo (or cache): a dictionary from a call's arguments to its answer; finding the answer there is a cache hit

Drawing the tree, step by step: fib(n) is fib(n - 1) + fib(n - 2), so every call above the base cases makes two calls. Watch the tree for fib(4) grow, one call at a time. The same colour means the same call again:

What it costs, by counting. Every call does a little work, so count the calls. fib(n) makes 1 call itself, plus all the calls of fib(n − 1) and fib(n − 2):

  • fib(5): 15 calls
  • fib(10): 177 calls
  • fib(20): 21,891 calls
  • fib(30): 2,692,537 calls

Each extra n multiplies the calls by about 1.6, because the tree for fib(n) holds the trees for fib(n − 1) and fib(n − 2) side by side. That is exponential time, O(1.6ⁿ): fib(40) needs about 331 million calls. Yet there are only n + 1 different questions, fib(0) to fib(n). Everything else is repeats.

Memoization, step by step:

  1. before doing any work, look on the shelf: if n in memo: return memo[n]
  2. otherwise work it out as before
  3. put the answer on the shelf before returning it: memo[n] = result

Now every repeat is answered from the shelf, and nothing grows under it:

Why it is correct. fib(k) always gives the same answer for the same k: it depends only on its argument (a pure function). So the answer on the shelf is exactly what the call would have worked out again. Memoizing a function whose answer depends on something else, like the time or a changing global, would hand back stale answers.

What it costs now. Each fib(k), k = 0 to n, is worked out once: n + 1 calls that do work. Each of those makes at most two calls, so there are at most about 2n calls in all, most of them instant shelf answers: O(n) time. The price is memory: the shelf holds n + 1 answers, and the stack still goes n frames deep: O(n) memory.

The code. The memo is a dictionary passed along, or Python's ready-made shelf from Chapter 27, functools.cache:

import functools

def fib(n, memo):
    if n in memo:                    # 1. on the shelf already?
        return memo[n]
    result = n if n < 2 else fib(n - 1, memo) + fib(n - 2, memo)
    memo[n] = result                 # 3. put it on the shelf
    return result

@functools.cache                     # the same shelf, ready-made
def fib2(n):
    return n if n < 2 else fib2(n - 1) + fib2(n - 2)

memo = {}
print(fib(80, memo), len(memo))
print(fib2(80))

def paths(rows, cols, memo):         # two arguments: the key is the pair
    if rows == 1 or cols == 1:
        return 1
    if (rows, cols) not in memo:
        memo[(rows, cols)] = paths(rows - 1, cols, memo) + paths(rows, cols - 1, memo)
    return memo[(rows, cols)]

print(paths(3, 3, {}), paths(16, 16, {}))

Mistakes and edge cases.

  • a key that leaves out an argument: with two arguments, memo[rows] mixes up different questions; use the pair (rows, cols) as the key
  • storing without checking (or checking without storing): the shelf only helps if you look at it first and fill it every time
  • memoizing an impure function: if the answer depends on anything other than the arguments, the shelf goes stale
  • memo shared by accident: def fib(n, memo={}) keeps one dictionary across all calls ever made; that works for fib, but is surprising elsewhere. Passing a fresh {} or using functools.cache is clearer

Quiz

  1. What does this print?

    calls = 0
    
    def fib(n):
        global calls
        calls += 1
        if n < 2:
            return n
        return fib(n - 1) + fib(n - 2)
    
    print(fib(4), calls)
  2. Inside the tree for fib(5), how many times is fib(2) called?

    • 3
    • 1
    • 2
    • 5
  3. What does memoization do to the number of calls for fib(n)?

    • From about 1.6ⁿ down to about 2n
    • It halves them
    • Nothing: it only saves memory
  4. fib(6, {}) should be 8, but it gives 6. Which line is wrong?

    def fib(n, memo):
        if n in memo:
            return memo[n]
        if n < 2:
            return n
        memo[n] = fib(n - 1, memo) + fib(n - 2, memo)
        return n
  5. With a memo, fib(n) takes O(n) time. How much memory?

    • O(n): the shelf holds n + 1 answers and the stack goes n deep
    • O(1)
    • O(1.6ⁿ)

Coding tasks

  1. Write count_calls(n): how many calls plain recursive fib(n) makes (fib(0) and fib(1) make 1; fib(n) makes 1 plus the calls of fib(n - 1) and fib(n - 2)). Your own function must be quick: count_calls(80) is about 76 thousand million million.

  2. From home at the top-left corner of a grid of city blocks to school at the bottom-right, you only walk right or down. Write paths(rows, cols): how many different routes there are (a grid with 1 row or 1 column has 1). Remember answers, so paths(16, 16) is quick.