Python 3D Academyবাংলা

Overlapping subproblems: climbing stairs, from recursion to memo

🌍 In real life. Rina climbs the 10 stairs to her flat, taking 1 or 2 stairs at a time. In how many different ways can she do it? Think about her last step: she arrived from stair 9 (a 1-step) or from stair 8 (a 2-step). So the ways to reach 10 are the ways to reach 9 plus the ways to reach 8. Each of those splits the same way. The question answers itself from smaller copies of the same question.

The idea in one sentence: dynamic programming (DP) solves a problem from the answers to smaller versions of it, and works out each smaller answer only once, because the same small questions come up again and again.

Its words:

  • subproblem: a smaller version of the question, like "ways to reach stair 8"
  • state: what names a subproblem; here just the stair number n
  • recurrence: the rule that builds an answer from smaller ones: ways(n) = ways(n − 1) + ways(n − 2)
  • base case: a subproblem answered directly: ways(0) = ways(1) = 1
  • overlapping subproblems: the same subproblem is needed many times
  • memoization (top-down DP): keep each answer in a dictionary the first time, and read it after that

Designing a DP, step by step:

  1. choose the state: what does one subproblem need to know?
  2. write the recurrence: how does a state's answer come from smaller states?
  3. write the base cases
  4. make sure each state is worked out once (a memo now, a table in Lesson 57.2)
  5. read the answer from the state that is the whole question

The plain recursion asks the same questions over and over. ways(n) makes exactly the same calls as fib(n) from Lesson 42.2; only the base answers differ. Here are the calls for n = 5: 15 of them, though there are only 6 different questions:

Now the same calls with a memo. The first time a question is answered it goes on the shelf, and every later call for it just reads the shelf, so the tree collapses to one chain:

When is a problem a DP problem? It needs two things. Optimal substructure: the answer to the whole is built from answers to subproblems (the ways to reach 10 come from the ways to reach 9 and 8). Overlapping subproblems: those subproblems repeat. Merge sort (Chapter 45) splits a problem too, but its halves never repeat, so a memo would save nothing there.

What it costs, by counting. Plain recursion makes 1, 1, 3, 5, 9, 15 calls for n = 0 to 5, and the count grows like the answers themselves: for n = 20, 21,891 calls, and for n = 40, over 330,000,000. With a memo each of the n + 1 states is worked out once, and each looks at two others, so about 2n steps: O(n). The price is O(n) memory for the memo.

def climb(n):
    if n < 2:                                  # 0 or 1 stairs: one way
        return 1
    return climb(n - 1) + climb(n - 2)         # last step was 1 stair, or 2

def climb_memo(n, memo):
    if n in memo:                              # worked out before: just read it
        return memo[n]
    result = 1 if n < 2 else climb_memo(n - 1, memo) + climb_memo(n - 2, memo)
    memo[n] = result                           # keep it for next time
    return result

def count_calls(n):
    if n < 2:
        return 1                               # this call, and nothing below it
    return 1 + count_calls(n - 1) + count_calls(n - 2)

print(climb(10), climb_memo(10, {}))
print(count_calls(5), count_calls(20))
print(climb_memo(80, {}))

Mistakes and edge cases.

  • a missing base case: without n < 2, the calls go below 0 and never stop (a RecursionError)
  • storing but never reading: memo[n] = result alone saves nothing; check n in memo first
  • a default memo of {}: def f(n, memo={}) shares one dictionary across every call of the program; pass a fresh one, or use functools.cache
  • deep recursion: a memo still recurses n deep; for n around 1,000 and more, Python's recursion limit stops it, which the table in Lesson 57.2 avoids

Quiz

  1. What two things make a problem a good fit for DP?

    • The answer is built from subproblem answers, and the subproblems repeat
    • The input is sorted, and small
    • The greedy choice is always safe
  2. What does this print?

    def count_calls(n):
        if n < 2:
            return 1                               # this call, and nothing below it
        return 1 + count_calls(n - 1) + count_calls(n - 2)
    
    print(count_calls(4))
  3. What does this print?

    def climb_memo(n, memo):
        if n in memo:                              # worked out before: just read it
            return memo[n]
        result = 1 if n < 2 else climb_memo(n - 1, memo) + climb_memo(n - 2, memo)
        memo[n] = result                           # keep it for next time
        return result
    
    memo = {}
    climb_memo(4, memo)
    print(memo[4], len(memo))
  4. With a memo, about how many steps does climb_memo(n) take?

    • O(n): each state is worked out once
    • O(2ⁿ), like the plain recursion
    • O(1)
  5. climb_memo(4, {}) gives 8 instead of 5. Which line is wrong?

    def climb_memo(n, memo):
        if n in memo:
            return memo[n]
        result = 1 if n < 2 else climb_memo(n - 1, memo) + climb_memo(n - 2, memo)
        memo[n - 1] = result
        return result

Coding tasks

  1. Write climb_memo(n, memo): the number of ways to climb n stairs taking 1 or 2 at a time, where memo is a dictionary from a stair number to its answer. Read memo before working anything out, and store every answer you work out in it. The tests also look inside memo.

  2. Write count_calls(n): how many calls the plain climb(n) above makes in total, counting the first call too. climb(0) and climb(1) make 1 call each.