Dynamic Programming: Work It Out Once, Write It Down, Read It Back
How many ways can Emma climb five stairs, one or two at a time? Plain recursion asks the same small questions again and again; a memo works each one out once. For 30 stairs that is 1,664,079 calls against 57.
What you will learn
- Break the climbing-stairs problem into smaller copies of itself
- Explain why plain recursion repeats work and how a memo stops it
- Add a memo to a recursive Python function and compare call counts
- Describe top-down and bottom-up dynamic programming and when a memo helps
Before you start
- Recursion
- Python lists and classes
- Big-O notation
Emma has a staircase with five stairs. She climbs one or two stairs at a time, never more. How many different ways can she get to the top?
List them all and look at the last move. In five of the ways, the last move is one stair. In the other three, it's two stairs. Five plus three is eight ways. That gives a neat rule: the ways for five stairs equal the ways for four stairs plus the ways for three stairs. To count five, we ask the same question for four and three, and those ask it for even smaller ones. That's recursion.
Write the answer down
Jack asks Emma, "How many ways to climb three stairs?" Emma counts them all and gets three. Then Tom asks the same question, and Emma counts them all again. Same work, twice. So Emma does something smart: the first time, she writes the answer in a notebook. When Kate asks, Emma just reads it. Three, no counting.
Work it out once, write it down, read it back. In code the notebook is called a memo, and the idea is dynamic programming.
The plain way
class PlainStairs:
def __init__(self):
self.calls = 0 # how many times ways() ran
def ways(self, n):
self.calls += 1
if n <= 2:
return n # 1 stair: 1 way, 2 stairs: 2 ways
return self.ways(n - 1) + self.ways(n - 2)
Small staircases answer directly: one stair, one way; two stairs, two ways. Otherwise the last move was one or two stairs, so add ways(n - 1) and ways(n - 2). calls counts every call.
Play ways(5): it asks for 4, which asks for 3, which asks for 2 (answer 2) and 1 (answer 1), so 3 stairs is 3. Then 4 also needs 2, so 4 stairs is 5. Now 5 needs ways(3). We worked that out already, but plain recursion doesn't remember, so it does it all again. Eight ways in nine calls, and 3 stairs was worked out twice.
Adding a memo
class MemoStairs:
def __init__(self):
self.calls = 0
self.memo = [0] * 100 # 0 means "not worked out yet"
def ways(self, n):
self.calls += 1
if n <= 2:
return n
if self.memo[n] != 0:
return self.memo[n] # seen it: remember!
self.memo[n] = self.ways(n - 1) + self.ways(n - 2)
return self.memo[n]
Only two lines more. The memo is a list where 0 means "not worked out yet". If memo[n] isn't zero, we've seen this question before, so return the answer at once. Otherwise work it out once and write it into memo[n]. (The list has room for 100 sizes, which is plenty here.)
from plain_stairs import PlainStairs
from memo_stairs import MemoStairs
plain = PlainStairs()
a = plain.ways(5)
print(f"Plain: {a} ways, {plain.calls} calls")
memo = MemoStairs()
b = memo.ways(5)
print(f"Memo: {b} ways, {memo.calls} calls")
Plain: 8 ways, 9 calls
Memo: 8 ways, 7 calls
With the memo, ways(3) is written down the first time. When it comes up again, the page says 3, and no calls happen below it. Every size is worked out only once.
A taller staircase
from plain_stairs import PlainStairs
from memo_stairs import MemoStairs
row = "{} stairs: plain {:>11,} calls, memo {} calls"
for n in (10, 20, 25, 30):
plain = PlainStairs()
plain.ways(n)
memo = MemoStairs()
memo.ways(n)
print(row.format(n, plain.calls, memo.calls))
10 stairs: plain 109 calls, memo 17 calls
20 stairs: plain 13,529 calls, memo 37 calls
25 stairs: plain 150,049 calls, memo 47 calls
30 stairs: plain 1,664,079 calls, memo 57 calls
For 30 stairs, the plain way makes over one and a half million calls; the memo way makes 57. Each extra stair makes the plain way about sixty percent more work, because the same small questions keep coming back. The memo adds only two calls per stair.
Filling the notebook from the bottom
There's a second way to use the same notebook. Start at the bottom and never ask a question twice:
| Stairs | Read the two pages before | Write |
|---|---|---|
| 1 | 1 | |
| 2 | 2 | |
| 3 | 2 + 1 | 3 |
| 4 | 3 + 2 | 5 |
| 5 | 5 + 3 | 8 |
Eight ways with only three additions, and nothing left waiting. Asking from the top and writing as you go (top-down, the memo above) and filling from the bottom (bottom-up) give the same answer.
What it costs
| Way | Time | Extra space |
|---|---|---|
| Plain recursion | grows like 2n, exploding | call stack only |
| Top-down with a memo | O(n), each size once | one memo cell per size |
| Bottom-up | O(n), one addition per stair | one page per size |
A little memory buys a huge amount of time. But a memo only pays off when the same small questions come back. Looking up a name in a sorted phone book asks a new question every time, so a notebook helps nobody there.
Where you meet it
- Spell checkers compare smaller pieces of two words and write each result down.
- Comparing two versions of a file builds what they share from smaller comparisons.
- Publishing software picks line breaks so the whole paragraph looks best.
- Some route finders build the best way to each junction from the junctions before it.
Where a greedy algorithm commits to one choice, dynamic programming keeps the answers to smaller problems and builds the best one from them.
Try it yourself
Ask both classes for 30 stairs and compare the call counts. Then print memo.memo[10] to see an answer the memo remembered.
Related courses on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Data Structures and Algorithms Concepts: No Coding Needed
How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)Related posts
Big-O: Reading Cost From Code, With Handshakes and a Guest Book
Big-O asks one question: how do the steps grow when the list grows? Check a school trip sheet for duplicates two ways, handshakes and a guest book, count every step in Python, then grow the list to ten thousand ids and watch 10,000 steps turn into almost 50 million.
Recursion: Russian Dolls, the Base Case and the Call Stack
Recursion means doing the same job on a smaller piece of the problem, and stopping at a base case. Count Emma's Russian dolls with a Python function that calls itself, watch each call wait on the call stack so the answers come back in reverse, then take the base case out and meet RecursionError.
Linear vs Binary Search: Page by Page, or Open in the Middle
Is kite a real word? Page by page takes 11 checks; opening in the middle takes 4. Trace binary search step by step, see a million words answered in 20 checks, and watch it give the wrong answer on an unsorted list.
Insertion Sort: Take the Next Card and Slide It Left Until It Fits
Emma's hand 7, 3, 9, 2, 5 sorted one card at a time in 6 shifts. Trace each card, see why a backwards hand costs the most, why 5,000 shuffled cards need over 6 million shifts, and why a sorted hand needs zero.
