Computer Science · Book 2 · Grades 10–12

High School Computer Science

High School Computer Science · Grades 10–12

28Dynamic Programming

The recursive fib of chapter 22 needs 2 692 5372\,692\,537 calls to compute fib(30)\mathrm{fib}(30), a number it could find by hand in 3030 additions. It is not slow because the problem is hard: it is slow because it solves the same small problems again and again, fib(2)\mathrm{fib}(2) alone 514 229514\,229 times, and forgets each answer as soon as it has used it. Writing the answers down fixes it.

This chapter makes that remedy a method. It applies whenever a problem splits into smaller problems that overlap: the fewest coins for an amount, where greedy failed; the longest part two texts have in common, and the fewest changes from one version of a text to the next; the best load of a knapsack with whole objects. Each time the work is a table filled in the right order, and its price is the memory of the table.

You already know

A recursive function is defined from its values on smaller inputs (chapter 22). A greedy algorithm takes the best-looking choice at each step, and fails for some coin systems and for the knapsack with whole objects (chapter 18). A grid is a list of lists, and a dictionary maps keys to values (Book 1, grades 8 and 9).

28.1 Overlapping subproblems

Definition 28.1 (Subproblem, dynamic programming)

A subproblem of a problem is the same problem on a smaller input, whose solution helps build the solution of the whole. Dynamic programming solves a problem whose subproblems overlap by solving each subproblem once, recording its solution, and building larger solutions from the recorded ones.

Divide and conquer (chapter 27) also uses subproblems, but the two halves of a merge sort never share any work. The two calls of fib(n), on n−1n - 1 and n−2n - 2, do: the first one computes fib(n−2)\mathrm{fib}(n - 2) on its way.

Definition 28.2 (Memoisation)

Memoisation is the recording of a function’s results in a table, usually a dictionary from arguments to results: the function looks the arguments up before computing, and stores the result before returning.

"""Fibonacci again: the naive recursion, then the same with a notebook of results."""
calls = 0


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


def fib_memo(n, memo=None):
    global calls
    calls += 1
    if memo is None:
        memo = {}
    if n in memo:                       # already computed: look it up
        return memo[n]
    value = n if n < 2 else fib_memo(n - 1, memo) + fib_memo(n - 2, memo)
    memo[n] = value                     # write it down before returning
    return value


if __name__ == "__main__":
    for n in [10, 20, 30]:
        calls = 0
        value = fib_naive(n)
        naive_calls = calls
        calls = 0
        fib_memo(n)
        print(f"fib({n}) = {value:6}   naive calls: {naive_calls:7}"
              f"   memo calls: {calls}")
    calls = 0
    print("fib(90) =", fib_memo(90), "  memo calls:", calls)
Listing 28.1. The naive recursion and the memoised one, both counting their calls. code/grade-12/07-dynamic-programming/listings/fib_memo.py
$ python fib_memo.py
fib(10) =     55   naive calls:     177   memo calls: 19
fib(20) =   6765   naive calls:   21891   memo calls: 39
fib(30) = 832040   naive calls: 2692537   memo calls: 59
fib(90) = 2880067194370816120   memo calls: 179
Output 28.1. The memoised version makes 2n−12n - 1 calls.
The 9 calls of the memoised fib(5), against 15 for the naive one. The first call on each value computes it, going down the left side; every later call on it finds it in the dictionary and returns at once, so the tree has no repeated subtree.
The 99 calls of the memoised fib(5), against 1515 for the naive one. The first call on each value computes it, going down the left side; every later call on it finds it in the dictionary and returns at once, so the tree has no repeated subtree.
Calls made by the two versions of fib(n), from figures/calls.py, with a scale that multiplies by 10 at each mark. The naive count is multiplied by about 1.6 at each step and passes 29 million at n = 35; the memoised count is 2n - 1, 69 at n = 35.
Calls made by the two versions of fib(n), from figures/calls.py, with a scale that multiplies by 1010 at each mark. The naive count is multiplied by about 1.61.6 at each step and passes 2929 million at n=35n = 35; the memoised count is 2n−12n - 1, 6969 at n=35n = 35.

Python can keep the notebook itself. The line @cache, written just above def, hands the function to functools.cache, which returns a version of it that records every result; cache_info reports how often the record was used.

from functools import cache


@cache                                  # Python keeps the notebook for us
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)


print(fib(90))
print(fib.cache_info())
Listing 28.2. The same memoisation, done by the standard library. code/grade-12/07-dynamic-programming/listings/fib_cache.py
$ python fib_cache.py
2880067194370816120
CacheInfo(hits=88, misses=91, maxsize=None, currsize=91)
Output 28.2. 9191 values computed, 8888 calls answered from the record.

28.2 The bottom-up table

The memoised function still recurses: fib(n) waits for fib(n - 1), which waits for fib(n - 2), down to 11. For large nn the chain of waiting calls is longer than Python allows. But the order in which the values are needed is known in advance: from small to large. Filling the table in that order needs no recursion at all.

"""Fibonacci bottom-up: fill the table from the small values upwards."""


def fib_table(n):
    table = [0] * (n + 1)
    if n >= 1:
        table[1] = 1
    for k in range(2, n + 1):           # table[k - 1] and table[k - 2] are ready
        table[k] = table[k - 1] + table[k - 2]
    return table


def fib_two(n):
    """The same, keeping only the last two values."""
    before, current = 0, 1
    for _ in range(n):
        before, current = current, before + current
    return before


if __name__ == "__main__":
    print(fib_table(12))
    print(fib_table(90)[90], fib_two(90))
    print("fib(1000) has", len(str(fib_two(1000))), "digits")
Listing 28.3. Fibonacci bottom-up, with the whole table and with two values. code/grade-12/07-dynamic-programming/listings/fib_table.py
$ python fib_table.py
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
2880067194370816120 2880067194370816120
fib(1000) has 209 digits
Output 28.3. The table up to 1212; fib(90)\mathrm{fib}(90) both ways; fib(1000)\mathrm{fib}(1000), far beyond the recursion limit.

Method 28.3 (Designing a dynamic programme)

(1) Say what one cell of the table means, in words: “best[a] is the fewest coins that make a”. (2) Write the recurrence: the value of a cell from cells of smaller subproblems, and the cells known directly. (3) Choose an order of filling in which every cell a cell needs is already filled. (4) Read the answer in the last cell, and, to know how it is achieved and not only its value, follow the choices back. (5) Count the cells: they are the memory, and, times the work per cell, the time.

Step (5) also shows what can be saved: fib_two keeps only the last two values, since no cell needs an older one. The same saving works whenever each row of a table needs only the row before it.

28.3 Change with the fewest coins

With the coins 11, 33 and 44, greedy pays 66 as 4+1+14 + 1 + 1, three coins, when 3+33 + 3 takes two (chapter 18). The subproblems are the smaller amounts. If a best way to pay aa uses a coin cc, the other coins pay a−ca - c, and must do so with as few coins as possible: otherwise a better way to pay a−ca - c would give a better way to pay aa. So

best(0)=0,best(a)=1+min⁡c≤abest(a−c)(a≥1),\mathrm{best}(0) = 0, \qquad \mathrm{best}(a) = 1 + \min_{c \le a} \mathrm{best}(a - c) \quad (a \ge 1),

the minimum running over the coins cc of the system that are at most aa.

"""Change with the fewest coins, for any coin system."""


def change_table(amount, coins):
    """best[a]: fewest coins for a; last[a]: one coin of a best way."""
    best = [0] + [None] * amount
    last = [None] * (amount + 1)
    for a in range(1, amount + 1):
        for c in coins:
            if c <= a and best[a - c] is not None:
                if best[a] is None or best[a - c] + 1 < best[a]:
                    best[a] = best[a - c] + 1
                    last[a] = c
    return best, last


def rebuild(amount, last):
    used = []
    while amount > 0:                   # follow the recorded choices back
        used.append(last[amount])
        amount -= last[amount]
    return used


if __name__ == "__main__":
    best, last = change_table(6, [1, 3, 4])
    print("amount:", list(range(7)))
    print("best:  ", best)
    print("last:  ", last)
    print("6 =", rebuild(6, last), "  greedy gave [4, 1, 1]")
    best, last = change_table(36, [1, 2, 5, 12, 25, 40])
    print("Brenmoor, 36 =", rebuild(36, last), "  greedy gave [25, 5, 5, 1]")
Listing 28.4. The table of fewest coins, and the coins rebuilt from the recorded choices. code/grade-12/07-dynamic-programming/listings/change_dp.py
$ python change_dp.py
amount: [0, 1, 2, 3, 4, 5, 6]
best:   [0, 1, 2, 1, 1, 2, 2]
last:   [None, 1, 1, 3, 4, 1, 3]
6 = [3, 3]   greedy gave [4, 1, 1]
Brenmoor, 36 = [12, 12, 12]   greedy gave [25, 5, 5, 1]
Output 28.4. Two coins for 66 where greedy used three; and 3636 in Brenmoor, the smallest amount greedy got wrong there.
The table for the coins 1, 3, 4, filled from left to right. best[6] = 2 came from best[3] + 1, and last[6] records the coin 3; the rebuild follows the recorded coins back from 6 to 3 to 0.
The table for the coins 11, 33, 44, filled from left to right. best[6] =2= 2 came from best[3] +1+ 1, and last[6] records the coin 33; the rebuild follows the recorded coins back from 66 to 33 to 00.

The table has a+1a + 1 cells, and each looks at every coin: for kk coins, about a×ka \times k steps. Trying all combinations of coins, as in chapter 18, took 36873687 combinations for 100100 in Brenmoor; the table takes about 600600 steps.

28.4 Common subsequences and alignments

Definition 28.4 (Longest common subsequence)

A subsequence of a sequence keeps some of its elements, in their order, and drops the others: LIBRY is a subsequence of LIBRARY. A longest common subsequence of two sequences is a sequence that is a subsequence of both, and as long as possible.

Let t[i][j]t[i][j] be the length of a longest common subsequence of the first ii letters of aa and the first jj of bb. If aa’s letter ii and bb’s letter jj are equal, one such subsequence ends with that letter, and t[i][j]=t[i−1][j−1]+1t[i][j] = t[i - 1][j - 1] + 1. If they differ, at least one of them is not the last letter of the subsequence and can be dropped: t[i][j]=max⁡(t[i−1][j],t[i][j−1])t[i][j] = \max(t[i - 1][j], t[i][j - 1]). A row or a column with no letters holds 00. Filling row by row from the top left, each cell finds the three cells it needs above it and on its left.

"""The longest common subsequence of two words, with its table."""


def lcs_table(a, b):
    n, m = len(a), len(b)
    t = [[0] * (m + 1) for _ in range(n + 1)]   # t[i][j]: for a[:i] and b[:j]
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            if a[i - 1] == b[j - 1]:
                t[i][j] = t[i - 1][j - 1] + 1
            else:
                t[i][j] = max(t[i - 1][j], t[i][j - 1])
    return t


def rebuild(a, b, t):
    i, j, out = len(a), len(b), []
    while i > 0 and j > 0:
        if a[i - 1] == b[j - 1]:
            out.append(a[i - 1])
            i, j = i - 1, j - 1
        elif t[i - 1][j] >= t[i][j - 1]:
            i -= 1
        else:
            j -= 1
    return "".join(reversed(out))


if __name__ == "__main__":
    a, b = "LIBRARY", "LITERARY"
    t = lcs_table(a, b)
    print("    " + " ".join(b))
    for i, row in enumerate(t):
        print((" " + a)[i], " ".join(str(x) for x in row))
    print("length", t[len(a)][len(b)], "subsequence", rebuild(a, b, t))
Listing 28.5. The table of common subsequences, and a longest one rebuilt. code/grade-12/07-dynamic-programming/listings/lcs.py
$ python lcs.py
    L I T E R A R Y
  0 0 0 0 0 0 0 0 0
L 0 1 1 1 1 1 1 1 1
I 0 1 2 2 2 2 2 2 2
B 0 1 2 2 2 2 2 2 2
R 0 1 2 2 2 3 3 3 3
A 0 1 2 2 2 3 4 4 4
R 0 1 2 2 2 3 4 5 5
Y 0 1 2 2 2 3 4 5 6
length 6 subsequence LIRARY
Output 28.5. LIBRARY and LITERARY share LIRARY, six letters.
The table of LIBRARY (rows) and LITERARY (columns). The shaded cells are the path of the rebuild, from the bottom right back to the top left; at each circled cell the two letters are equal, and that letter belongs to the subsequence: L, I, R, A, R, Y.
The table of LIBRARY (rows) and LITERARY (columns). The shaded cells are the path of the rebuild, from the bottom right back to the top left; at each circled cell the two letters are equal, and that letter belongs to the subsequence: L, I, R, A, R, Y.

A second question about two versions of a text is how many changes turn one into the other.

Definition 28.5 (Edit distance, alignment)

The edit distance between two sequences is the smallest number of operations that turn the first into the second, each operation inserting one element, deleting one, or replacing one by another. An alignment of two sequences writes them one above the other, with gaps, so that each column holds two equal elements, two different ones (a replacement), or an element and a gap (an insertion or a deletion).

The table has the same shape. d[i][j]d[i][j] is the distance from the first ii elements of aa to the first jj of bb. In a best alignment, the last column either pairs aa’s element ii with bb’s element jj, for no cost if they are equal and 11 otherwise; or holds aa’s element ii over a gap, a deletion; or a gap over bb’s element jj, an insertion. So d[i][j]d[i][j] is the smallest of d[i−1][j−1]d[i - 1][j - 1] (plus 11 if the elements differ), d[i−1][j]+1d[i - 1][j] + 1 and d[i][j−1]+1d[i][j - 1] + 1; and d[i][0]=id[i][0] = i, d[0][j]=jd[0][j] = j. The elements can be letters, or the words of a sentence.

"""Edit distance between two sequences, and the alignment that achieves it."""


def distance_table(a, b):
    n, m = len(a), len(b)
    d = [[0] * (m + 1) for _ in range(n + 1)]   # d[i][j]: from a[:i] to b[:j]
    for i in range(n + 1):
        d[i][0] = i                             # delete all i items
    for j in range(m + 1):
        d[0][j] = j                             # insert all j items
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            change = 0 if a[i - 1] == b[j - 1] else 1
            d[i][j] = min(d[i - 1][j - 1] + change,   # keep or replace
                          d[i - 1][j] + 1,            # delete a[i - 1]
                          d[i][j - 1] + 1)            # insert b[j - 1]
    return d


def alignment(a, b, d):
    """Pairs (x, y) from the end back; None marks a gap."""
    i, j, pairs = len(a), len(b), []
    while i > 0 or j > 0:
        if i > 0 and j > 0 and a[i - 1] == b[j - 1] and d[i][j] == d[i - 1][j - 1]:
            pairs.append((a[i - 1], b[j - 1]))        # kept
            i, j = i - 1, j - 1
        elif i > 0 and d[i][j] == d[i - 1][j] + 1:
            pairs.append((a[i - 1], None))            # deleted
            i -= 1
        elif j > 0 and d[i][j] == d[i][j - 1] + 1:
            pairs.append((None, b[j - 1]))            # inserted
            j -= 1
        else:
            pairs.append((a[i - 1], b[j - 1]))        # replaced
            i, j = i - 1, j - 1
    return pairs[::-1]
Listing 28.6. The distance table, and an alignment rebuilt from it. code/grade-12/07-dynamic-programming/listings/align.py
def show(pairs):
    """Three lines: the first version, the marks, the second version."""
    top, mid, bottom = [], [], []
    for x, y in pairs:
        width = max(len(x or "-"), len(y or "-"))
        top.append((x or "-" * width).ljust(width))
        mid.append(("|" if x == y else " " if x is None or y is None else "*") * width)
        bottom.append((y or "-" * width).ljust(width))
    return top, mid, bottom


if __name__ == "__main__":
    a = "the market opens at seven on sundays".split()
    b = "the new market opens at eight on sunday".split()
    d = distance_table(a, b)
    print("distance in words:", d[len(a)][len(b)])
    for line in show(alignment(a, b, d)):
        print(" ".join(line).rstrip())
Listing 28.7. Printing an alignment of two sentences, word by word. code/grade-12/07-dynamic-programming/listings/align.py
$ python align.py
distance in words: 3
the --- market opens at seven on sundays
|||     |||||| ||||| || ***** || *******
the new market opens at eight on sunday
Output 28.6. Three changes: one word inserted, two words replaced. The marks are | for a word kept and * for a word replaced.

Several alignments can reach the same distance. The rebuild keeps an element whenever it can, and otherwise prefers a gap to a replacement, which keeps the alignment close to what a reader would write.

28.5 The knapsack with whole objects

A knapsack holds at most WW kilograms; each object has a mass and a value, and is taken whole or left. Greedy by value per kilogram fails here (chapter 18): with 1010 kilograms, it takes the object of 66 kg worth 3030 and then nothing fits, when two objects of 55 kg worth 2020 each give 4040. Trying every subset is exact, but there are 2n2^n of them.

The subproblems use fewer objects and less room. Let k[i][w]k[i][w] be the best value with the first ii objects and at most ww kilograms. Object ii is left, and then k[i][w]=k[i−1][w]k[i][w] = k[i - 1][w]; or, if it fits, taken, and then the rest is the best load of ww minus its mass with the objects before it. The table is filled row by row, each row from the one above.

"""The 0/1 knapsack: best value with whole objects, by a table."""
from itertools import combinations


def knapsack(objects, capacity):
    """k[i][w]: best value with the first i objects and at most w kilograms."""
    n = len(objects)
    k = [[0] * (capacity + 1) for _ in range(n + 1)]
    for i in range(1, n + 1):
        _, kg, value = objects[i - 1]
        for w in range(capacity + 1):
            k[i][w] = k[i - 1][w]                     # without object i
            if kg <= w and k[i - 1][w - kg] + value > k[i][w]:
                k[i][w] = k[i - 1][w - kg] + value    # with object i
    return k


def chosen(objects, k, capacity):
    names, w = [], capacity
    for i in range(len(objects), 0, -1):              # from the last object back
        if k[i][w] != k[i - 1][w]:                    # object i was taken
            names.append(objects[i - 1][0])
            w -= objects[i - 1][1]
    return names[::-1]


def every_subset(objects, capacity):
    return max(sum(o[2] for o in s) for r in range(len(objects) + 1)
               for s in combinations(objects, r) if sum(o[1] for o in s) <= capacity)

Listing 28.8. The knapsack table, the objects rebuilt, and every subset as a check. code/grade-12/07-dynamic-programming/listings/knapsack_dp.py
if __name__ == "__main__":
    small = [("A", 6, 30), ("B", 5, 20), ("C", 5, 20)]
    k = knapsack(small, 10)
    for i, row in enumerate(k):
        print(i, " ".join(f"{x:2}" for x in row))
    print("best", k[3][10], chosen(small, k, 10))
    pack = [("tent", 5, 60), ("stove", 3, 50), ("rope", 4, 40), ("camera", 2, 45),
            ("books", 6, 30), ("food", 4, 70), ("lamp", 1, 15), ("chair", 5, 35)]
    k = knapsack(pack, 15)
    print("best", k[len(pack)][15], chosen(pack, k, 15), "| every subset:",
          every_subset(pack, 15))
Listing 28.9. The small case of the greedy chapter, then a pack of eight objects. code/grade-12/07-dynamic-programming/listings/knapsack_dp.py
$ python knapsack_dp.py
0  0  0  0  0  0  0  0  0  0  0  0
1  0  0  0  0  0  0 30 30 30 30 30
2  0  0  0  0  0 20 30 30 30 30 30
3  0  0  0  0  0 20 30 30 30 30 40
best 40 ['B', 'C']
best 240 ['tent', 'stove', 'camera', 'food', 'lamp'] | every subset: 240
Output 28.7. The table of the small case, row ii for the first ii objects; then 240240 in 1515 kg, as every subset finds.
The table of the small case, objects in rows, mass allowed in columns. 40 in the last cell differs from the 30 above it, so C was taken, leaving 5 kg; 20 in row B differs from the 0 above it, so B was taken, leaving 0 kg; A was left.
The table of the small case, objects in rows, mass allowed in columns. 4040 in the last cell differs from the 3030 above it, so C was taken, leaving 55 kg; 2020 in row B differs from the 00 above it, so B was taken, leaving 00 kg; A was left.

The table has (n+1)(W+1)(n + 1)(W + 1) cells and each takes a few steps: for 88 objects and 1515 kg, 144144 cells against 256256 subsets. The cost grows with WW, the size of the knapsack, not only with the number of objects: masses to the gram in a 1515 kg knapsack make 15 00115\,001 columns. Tables of two whole texts grow faster still.

"""How big do the tables get? Cells of an n x m table, and of two rows."""
import sys

row = [0] * 1001
print("one list of 1001 numbers:", sys.getsizeof(row), "bytes: 8 per cell, plus 56")
print(f"{'n = m':>8} {'cells (n+1)^2':>18} {'bytes, 8 each':>18} {'two rows':>9}")
for n in [10, 100, 1000, 10_000, 100_000, 1_000_000]:
    cells = (n + 1) * (n + 1)
    print(f"{n:8} {cells:18,} {8 * cells:18,} {2 * (n + 1):9,}")
Listing 28.10. The memory of an n×nn \times n table, and of two rows. code/grade-12/07-dynamic-programming/listings/table_sizes.py
$ python table_sizes.py
one list of 1001 numbers: 8064 bytes: 8 per cell, plus 56
   n = m      cells (n+1)^2      bytes, 8 each  two rows
      10                121                968        22
     100             10,201             81,608       202
    1000          1,002,001          8,016,008     2,002
   10000        100,020,001        800,160,008    20,002
  100000     10,000,200,001     80,001,600,008   200,002
 1000000  1,000,002,000,001  8,000,016,000,008 2,000,002
Output 28.8. Two texts of a million words would need eight terabytes for the whole table, and 1616 megabytes for two rows.

The distance needs only the row above: two rows are enough, as for fib_two. The alignment does not: the rebuild walks back through the whole table. Keeping both the small memory and the alignment is possible, by a cleverer method that is out of reach here.

History — Bellman, 1954

Richard Bellman published “The theory of dynamic programming”, an early general account of the method, in 1954 in the Bulletin of the American Mathematical Society. In its title, programming means planning a sequence of decisions, as in a schedule, not writing code.

28.6 Exercises

Exercise 28.1 ★

How many calls does fib_memo(6) make? And fib_naive(6)?

Solution

Solution of Exercise 28.1.

11=2×6−111 = 2 \times 6 - 1: one computing call for each of 6,5,…,06, 5, \dots, 0, and a lookup for each of 4,3,2,14, 3, 2, 1 (the second call made by 6,5,4,36, 5, 4, 3). The naive version makes 2525: 1515 for fib(5), 99 for fib(4), and the call on 66 itself.

Exercise 28.2 ★

Fill the table best for the coins 11, 33, 44 up to the amount 77. Which coins pay 77?

Solution

Solution of Exercise 28.2.

best for 00 to 77: 0,1,2,1,1,2,2,20, 1, 2, 1, 1, 2, 2, 2. For 77: 1+best(6)=31 + \mathrm{best}(6) = 3, 1+best(4)=21 + \mathrm{best}(4) = 2, 1+best(3)=21 + \mathrm{best}(3) = 2; the coin 33 is recorded first, and 7=3+47 = 3 + 4.

Exercise 28.3 ★

Find a longest common subsequence of STATION and NATIONS, and its length.

Solution

Solution of Exercise 28.3.

The subsequence ATION, of 55 letters: it comes after ST in STATION, and after N in NATIONS. The last cell of the table of the two words is 55, so none is longer.

Exercise 28.4 ★

In the knapsack table of the small case, from which cells is k[2][10]=30k[2][10] = 30 computed?

Solution

Solution of Exercise 28.4.

From k[1][10]=30k[1][10] = 30 (B left) and k[1][5]+20=0+20k[1][5] + 20 = 0 + 20 (B taken, leaving 55 kg for A alone, which does not fit). The larger is 3030.

Exercise 28.5 ★

Write binomial(n, k), memoised, from Pascal’s rule (nk)=(n−1k−1)+(n−1k)\binom{n}{k} = \binom{n-1}{k-1} + \binom{n-1}{k}, with (n0)=(nn)=1\binom{n}{0} = \binom{n}{n} = 1.

Solution

Solution of Exercise 28.5.

def binomial(n, k, memo=None):

if memo is None:

memo = {}

if k == 0 or k == n:

return 1

if (n, k) not in memo:

memo[(n, k)] = binomial(n - 1, k - 1, memo) + binomial(n - 1, k, memo)

return memo[(n, k)]

The key is the pair of arguments. The tests compare it with math.comb for all k≤n≤11k \le n \le 11.

Exercise 28.6 ★★

A student memoises binomial with memo[n] instead of memo[(n, k)]. The call binomial_bad(10, 5) returns 9696. Explain.

Solution

Solution of Exercise 28.6.

The result depends on both nn and kk, but the key records only nn. The first call on a row, say n=7n = 7, stores its value in memo[7]; every later call on row 77, whatever its kk, returns that same value. The wrong values of the lower rows are added up the rows, and give 9696 instead of 252252. A memo key must hold every argument the result depends on.

Exercise 28.7 ★★

Write min_coins(amount, coins) top-down, as a memoised recursion, returning None when the amount cannot be paid.

Solution

Solution of Exercise 28.7.

def min_coins(amount, coins, memo=None):

if memo is None:

memo = {}

if amount == 0:

return 0

if amount not in memo:

options = [min_coins(amount - c, coins, memo)

for c in coins if c <= amount]

options = [x for x in options if x is not None]

memo[amount] = min(options) + 1 if options else None

return memo[amount]

The tests compare it with the table and with trying every combination, for four coin systems.

Exercise 28.8 ★★

A student fills the table of lcs_table with range(n, 0, -1) and range(m, 0, -1), the same recurrence otherwise. On LIBRARY and LITERARY the answer is 11. Why?

Solution

Solution of Exercise 28.8.

Filling from the bottom right, the cell t[i][j]t[i][j] is computed before the cells t[i−1][j−1]t[i - 1][j - 1], t[i−1][j]t[i - 1][j] and t[i][j−1]t[i][j - 1] it reads, which still hold their starting 00. Each cell sees only zeros, so it is 11 if the letters are equal and 00 otherwise; the last cell, Y with Y, gives 11. The recurrence was right; the order of filling was not.

Exercise 28.9 ★★

How many paths go from the top-left corner to the bottom-right corner of a grid of 5×55 \times 5 squares, along its lines, moving only right or down? Set up a table.

Solution

Solution of Exercise 28.9.

Let p[r][c]p[r][c] be the number of paths to the crossing rr lines down and cc across. The first row and column hold 11; a path to any other crossing arrives from above or from the left, so p[r][c]=p[r−1][c]+p[r][c−1]p[r][c] = p[r - 1][c] + p[r][c - 1]. The rows are Pascal’s triangle read diagonally, and p[5][5]=252p[5][5] = 252, the number of ways to choose which 55 of the 1010 moves go right.

Exercise 28.10 ★★

Write diff_lines(old, new), which lists the lines of two versions of a file: lines kept with two spaces in front, lines deleted with -, lines added with +, using a longest common subsequence of the lines.

Solution

Solution of Exercise 28.10.

def diff_lines(old, new):

t = lcs_table(old, new)

i, j, out = len(old), len(new), []

while i > 0 or j > 0:

if i > 0 and j > 0 and old[i - 1] == new[j - 1]:

out.append(" " + old[i - 1])

i, j = i - 1, j - 1

elif j > 0 and (i == 0 or t[i][j - 1] >= t[i - 1][j]):

out.append("+ " + new[j - 1])

j -= 1

else:

out.append("- " + old[i - 1])

i -= 1

return out[::-1]

lcs_table works on lists of lines as well as on strings. The lines kept form a longest common subsequence, so the number of lines marked is as small as possible. The tests check that the kept and deleted lines give back old, and the kept and added ones new.

Exercise 28.11 ★★

The program of the chapter prints the lines of show, joined by spaces. What does it print for the letters of kitten and sitting? What is their distance?

Solution

Solution of Exercise 28.11.

k i t t e n -

* | | | * |

s i t t i n g

The space under the last letter marks the insertion. The distance is 33: k replaced by s, e by i, and g inserted.

Exercise 28.12 ★★★

Prove, by induction on aa, that change_table gives the fewest coins for every amount aa that can be paid.

Solution

Solution of Exercise 28.12.

Write opt(a)\mathrm{opt}(a) for the fewest coins that pay aa. For a=0a = 0, best[0] =0= 0. Let a≥1a \ge 1 be payable, and assume best is right for all smaller amounts. Every value best[a - c] + 1 the loop considers is the number of coins of a real way to pay aa: a best way for a−ca - c, plus cc. So best[a] ≥opt(a)\ge \mathrm{opt}(a). Take a best way to pay aa and one of its coins cc: the others pay a−ca - c, with opt(a)−1\mathrm{opt}(a) - 1 coins, so opt(a−c)≤opt(a)−1\mathrm{opt}(a - c) \le \mathrm{opt}(a) - 1. The loop considers cc and finds best[a - c] + 1 ≤opt(a)\le \mathrm{opt}(a). Hence best[a] =opt(a)= \mathrm{opt}(a). An amount that cannot be paid keeps None, since no best[a - c] is a number.

Exercise 28.13 ★★★

Write edit_operations(a, b), the list of operations of a best alignment, such as "replace k by s". Check that it has as many operations as the distance.

Solution

Solution of Exercise 28.13.

def edit_operations(a, b):

ops = []

for x, y in alignment(a, b, distance_table(a, b)):

if x is None:

ops.append(f"insert {y}")

elif y is None:

ops.append(f"delete {x}")

elif x != y:

ops.append(f"replace {x} by {y}")

return ops

Each column that is not a kept element is one operation, and the costs of the columns add up to the distance (question 13 of the problem). kitten, sitting gives replace k by s, replace e by i, insert g. The tests compare the number of operations with the distance on 150150 random pairs.

Exercise 28.14 ★★★

Count the cells and the steps of knapsack for nn objects and a capacity WW. A removal van holds 33 tonnes; its 4040 boxes are weighed to the kilogram, then to the gram. How many cells in each case? What does it say about the cost?

Solution

Solution of Exercise 28.14.

(n+1)(W+1)(n + 1)(W + 1) cells, each a comparison and an addition or two: the time and the memory grow like n×Wn \times W. In kilograms: 41×3001=123 04141 \times 3001 = 123\,041 cells, nothing for a computer. In grams: 41×3 000 001=123 000 04141 \times 3\,000\,001 = 123\,000\,041, about a gigabyte at 88 bytes per cell. The answer can be the same, yet the work is a thousand times larger: the cost depends on the size of the number WW, not on how many digits it takes to write it. Adding three digits to WW multiplies the cost by a thousand.

Exercise 28.15 ★★★

Write longest_increasing(t), which returns a longest strictly increasing subsequence of a list, with a table of the longest one ending at each position and a rebuild. Count its steps.

Solution

Solution of Exercise 28.15.

def longest_increasing(t):

if not t:

return []

best, before = [1] * len(t), [None] * len(t)

for i in range(len(t)):

for j in range(i):

if t[j] < t[i] and best[j] + 1 > best[i]:

best[i], before[i] = best[j] + 1, j

i = max(range(len(t)), key=lambda k: best[k])

out = []

while i is not None:

out.append(t[i])

i = before[i]

return out[::-1]

best[i] is the length of a longest increasing subsequence ending at t[i]: it extends the best one ending at a smaller earlier element. before records which, for the rebuild. The two loops make n(n−1)/2n(n - 1)/2 comparisons. For [5,2,8,6,3,6,9,7][5, 2, 8, 6, 3, 6, 9, 7]: [2,3,6,9][2, 3, 6, 9].

28.7 Problem: Aligning Two Versions

Problem 28.1

Weekend problem — what changed in the notice?

The library on Town Square has rewritten its notice. The program compares the two versions word by word, with the tables of the chapter, and prints only the columns of the alignment that changed.

"""Two versions of a notice: how far apart are they, word by word?"""
from align import alignment, distance_table
from lcs import lcs_table

OLD = """The library on Town Square opens at nine every morning except Sunday. Children
may borrow four books at a time for three weeks. Late books cost ten cents a day.
The reading room on the first floor closes at six, and the archive is open on
Tuesday and Thursday afternoons by appointment only."""

NEW = """The library on Town Square opens at eight every morning except Sunday and
Monday. Children may borrow six books at a time for three weeks. Late books cost
nothing. The reading room on the second floor closes at seven, and the
archive is open on Tuesday afternoons by appointment."""


def distance_two_rows(a, b):
    """The same distance, keeping only the previous row of the table."""
    previous = list(range(len(b) + 1))
    for i in range(1, len(a) + 1):
        current = [i] + [0] * len(b)
        for j in range(1, len(b) + 1):
            change = 0 if a[i - 1] == b[j - 1] else 1
            current[j] = min(previous[j - 1] + change, previous[j] + 1,
                             current[j - 1] + 1)
        previous = current
    return previous[len(b)]


a, b = OLD.split(), NEW.split()
n, m = len(a), len(b)
print("words:", n, "and", m, "| common subsequence:", lcs_table(a, b)[n][m], "words")
d = distance_table(a, b)
print("edit distance:", d[n][m], "| with two rows:", distance_two_rows(a, b))
for x, y in alignment(a, b, d):
    if x != y:
        print(f"  {x or '':>14} -> {y or ''}")
print("cells: full table", (n + 1) * (m + 1), "| two rows", 2 * (m + 1))
Listing 28.11. The two versions, compared word by word. code/grade-12/07-dynamic-programming/listings/versions.py
$ python versions.py
words: 53 and 49 | common subsequence: 40 words
edit distance: 15 | with two rows: 15
            nine -> eight
         Sunday. -> Sunday
                 -> and
                 -> Monday.
            four -> six
             ten -> nothing.
           cents -> 
               a -> 
            day. -> 
           first -> second
            six, -> seven,
             and -> 
        Thursday -> 
     appointment -> appointment.
           only. -> 
cells: full table 2700 | two rows 100
Output 28.9. Words, common words, distance, the changed columns, and the size of the tables.

Part I — The two versions.

  1. Read the two notices. List, in your own words, what the library changed.
  2. Why does the program compare words and not letters?
  3. Sunday. and Sunday count as different words. Why? What would change if the program removed the punctuation first?

Part II — Common words.

  1. What does lcs_table(a, b)[n][m] measure here?
  2. How many words of the old version are not in the common subsequence? Of the new one?
  3. Why is the edit distance at least the larger of these two numbers, and at most their sum?

Part III — The distance and the alignment.

  1. Count the replacements, deletions and insertions in the printed columns. Check the distance.
  2. The deleted words cents a day. come after ten -> nothing.. Give another alignment of the same cost for these words.
  3. Why is appointment -> appointment. a replacement?
  4. Thursday and and are deleted. Write the columns of the alignment around them.
  5. Each row of the distance table is filled from left to right. Which cells does d[i][j]d[i][j] need, and why is this order right?
  6. The rebuild starts at the bottom-right cell. Why does it never leave the table, and why does it stop?
  7. Prove that a column holding two different words in the rebuilt alignment costs one change, and that the total of the costs is d[n][m]d[n][m].

Part IV — Memory.

  1. How many cells has the full table? How many bytes, at 88 bytes per cell?
  2. Explain distance_two_rows: what does previous hold at the start of each pass of the loop?
  3. Why can the two-row version give the distance but not the alignment?
  4. Two versions of a book of 100 000100\,000 words each: memory of the full table, and of two rows?
  5. Time: how many cells are computed in each version? Did saving memory cost time?
  6. The tests compare distance_two_rows with the full table on 150150 random pairs. Why is that a convincing check?
  7. State the result: the distance between the two notices, the common words, and the cells of the two tables.
Solution

Solution of Problem 28.1.

1. The library opens at eight instead of nine, and is closed on Mondays as well as Sundays; children may borrow six books instead of four; late books cost nothing; the reading room is on the second floor and closes at seven; the archive opens on Tuesday afternoons only, and the word “only” after “appointment” has gone.

2. A word is a unit a reader notices; letter by letter, the alignment would match letters of unrelated words, such as the e of seven and of eight, and the table would have about 2525 times more cells.

3. The words are compared as strings, and the full stop is a character of the second. Removing the punctuation first, the program finds 1313: Sunday is kept, and and Monday are inserted, and appointment is kept with only deleted.

4. The largest number of words that both versions contain in the same order: 4040.

5. 53−40=1353 - 40 = 13 of the old version, 49−40=949 - 40 = 9 of the new one.

6. The kept columns of any alignment form a common subsequence, of at most 4040 words: at least 1313 old words are deleted or replaced, one operation each, so at least 1313 operations. Deleting the 1313 and inserting the 99 always works: at most 2222.

7. Replacements: nine, Sunday., four, ten, first, six,, appointment: 77. Deletions: cents, a, day., and, Thursday, only.: 66. Insertions: and, Monday.: 22. Total 1515, the printed distance.

8. Delete ten, cents and a, and replace day. by nothing.: still four operations.

9. appointment. has a full stop, so the two strings differ: the column pairs two different words.

10. Tuesday over Tuesday; and over a gap; Thursday over a gap; afternoons over afternoons.

11. d[i−1][j−1]d[i - 1][j - 1] and d[i−1][j]d[i - 1][j], in the row above, filled during the previous pass; and d[i][j−1]d[i][j - 1], just to the left, filled earlier in the same pass. The first row and column are filled before the loops.

12. Each step lowers ii, jj or both by 11. A step that lowers jj is taken only with j>0j > 0; when i=0i = 0 the insertion test holds, since d[0][j]=d[0][j−1]+1d[0][j] = d[0][j - 1] + 1, and when j=0j = 0 the deletion test holds. So neither goes below 00, and the loop stops when both are 00, after at most n+mn + m steps.

13. A kept column moves to a cell of equal value; a deletion or an insertion to a cell of value one less. The last branch is taken only when the three tests failed, so by the recurrence d[i][j]=d[i−1][j−1]+1d[i][j] = d[i - 1][j - 1] + 1 with two different words: one change. Along the path from d[n][m]d[n][m] to d[0][0]=0d[0][0] = 0, the value drops by the cost of each column, and the costs add up to d[n][m]d[n][m].

14. 54×50=270054 \times 50 = 2700 cells, 21 60021\,600 bytes.

15. At the start of pass ii, previous is row i−1i - 1: the distances from the first i−1i - 1 words of a to each beginning of b. The pass builds row ii in current, which becomes previous.

16. The rebuild walks back from the last cell through every row, and the earlier rows are gone.

17. 100 0012≈1010100\,001^2 \approx 10^{10} cells, about 8080 gigabytes; two rows of 100 001100\,001 cells, about 1.61.6 megabytes.

18. Both compute the same 53×49=259753 \times 49 = 2597 cells; the saving costs no extra time.

19. The two programs are written differently, and they agree on 150150 pairs of all shapes, empty sequences included; the full table is itself checked against the alignment it produces and, for the common subsequences, against trying every subsequence.

20. The two notices, of 5353 and 4949 words, share 4040 words in order and are 1515 word changes apart: 77 replacements, 66 deletions and 22 insertions. The full table has 27002700 cells; keeping two rows, 100100 cells give the same distance.

Terms defined in this chapter

See all 1050 terms in the glossary