Skip to content
KALANBLON
Show contents

Chapter 5 of 7 · 20 min

Dynamic programming

By the end of this chapter, you'll be able to

  • Spot subproblems that repeat in a recursion
  • Remember the results already computed (memoisation)
  • Build a solution with a table, from the smallest to the largest
  • Explain why a greedy algorithm can fail

The cost of repeated computations

The Fibonacci sequence (0, 1, 1, 2, 3, 5, 8, 13…) is defined recursively: each term is the sum of the two previous ones. The direct version is elegant, but let's count its calls:

calls = 0

def fib(n):
    global calls
    calls += 1
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

for n in (10, 20, 25):
    calls = 0
    print(f"fib({n}) = {fib(n)} in {calls} calls")
fib(10) = 55 in 177 calls
fib(20) = 6765 in 21891 calls
fib(25) = 75025 in 242785 calls

To compute fib(25), almost 250,000 calls are needed, whereas there are only 26 different values to know. fib(23) is computed 2 times, fib(22) 3 times, fib(21) 5 times… The number of calls grows exponentially: about ×1.6 for each extra rank.

Remember: memoisation

A simple idea: the first time fib(k) is computed, store the result in a dictionary. The next times, read it back. This is memoisation:

from functools import lru_cache

memo = {}
def fib_memo(n):
    if n < 2:
        return n
    if n not in memo:
        memo[n] = fib_memo(n - 1) + fib_memo(n - 2)
    return memo[n]

@lru_cache(maxsize=None)
def fib_cache(n):
    return n if n < 2 else fib_cache(n - 1) + fib_cache(n - 2)

print(fib_memo(25), len(memo), "values stored")
print(fib_cache(90))
75025 24 values stored
2880067194370816120

Each value is computed only once: we go from exponential time to linear time. fib(90) would be out of reach in the naive version (billions of billions of calls), here it is immediate. The functools.lru_cache decorator does the memoisation for you.

Each subproblem is solved only once: the computation becomes linear.

Step 5 of 5
Text description of the animation
  1. We want the 25th term.
  2. It breaks down into two smaller subproblems of the same kind.
  3. The same subproblems keep coming back in the call tree.
  4. Each result is stored as soon as it is known.
  5. Each subproblem is solved only once: the computation becomes linear.

Build a table: making change

You can also solve the subproblems in order, from the smallest to the largest, by filling a table. Example: with coins of 1, 3 and 4, what is the minimum number of coins to make an amount? For each amount m, try each coin c: it will take 1 coin, plus the best change for m − c, already computed.

def min_change(amount, coins):
    INFINITY = float("inf")
    best = [0] + [INFINITY] * amount
    choice = [None] * (amount + 1)
    for m in range(1, amount + 1):
        for c in coins:
            if c <= m and best[m - c] + 1 < best[m]:
                best[m] = best[m - c] + 1
                choice[m] = c
    change, m = [], amount
    while m > 0:
        change.append(choice[m])
        m -= choice[m]
    return best[amount], change

print(min_change(6, [1, 3, 4]))
print(min_change(10, [1, 3, 4]))
(2, [3, 3])
(3, [3, 3, 4])

best[m] holds the minimum number of coins for the amount m, and choice[m] the last coin used, which lets you rebuild the change by going back. For an amount M and k kinds of coins, the computation takes M × k steps.

Mini-lab: greedy versus dynamicPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: paths in a grid

A delivery rider starts from the top-left corner of a grid neighbourhood of 4 streets by 5 and must reach the opposite corner, moving only right or down. How many different paths are there? Compute it with dynamic programming, for a grid of rows × columns intersections.

Hint 1
An intersection can only be reached from the one above or the one on the left.
Hint 2
paths[i][j] = paths[i-1][j] + paths[i][j-1], with 1 path for each intersection of the first row and the first column.
Show the solution and common mistakes
def count_paths(rows, columns):
    paths = [[1] * columns for _ in range(rows)]
    for i in range(1, rows):
        for j in range(1, columns):
            paths[i][j] = paths[i - 1][j] + paths[i][j - 1]
    return paths[-1][-1]

print(count_paths(4, 5), count_paths(3, 3), count_paths(10, 10))
35 6 48620

For 4 × 5 intersections, there are 35 paths. A naive recursive exploration would recompute the same intersections over and over; the table computes each one once, in rows × columns steps.

Common mistakes:

  • Initialising the whole table to 0: the first row and the first column must be 1 (there is only one way to follow them), otherwise everything stays 0.
  • Creating the table with [[1] * columns] * rows: every row would be the same list, and changing one would change the others.

Summary

  1. 1When a recursion recomputes the same subproblems, its cost can become exponential.
  2. 2Memoisation stores each computed result; functools.lru_cache does it automatically.
  3. 3You can also fill a table from the smallest subproblem to the largest.
  4. 4A greedy algorithm makes the best immediate choice, without backtracking: it can be wrong.
  5. 5Dynamic programming = repeating subproblems + memory of the results.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.