High School Computer Science · Grades 10–12
28Dynamic Programming
The recursive fib of chapter 22 needs calls to compute , a number it could find by hand in additions. It is not slow because the problem is hard: it is slow because it solves the same small problems again and again, alone 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 and , do: the first one computes 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)
$ 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
fib(5), against 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.fib(n), from figures/calls.py, with a scale that multiplies by at each mark. The naive count is multiplied by about at each step and passes million at ; the memoised count is , at .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())
$ python fib_cache.py
2880067194370816120
CacheInfo(hits=88, misses=91, maxsize=None, currsize=91)
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 . For large 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")
$ python fib_table.py
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
2880067194370816120 2880067194370816120
fib(1000) has 209 digits
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 , and , greedy pays as , three coins, when takes two (chapter 18). The subproblems are the smaller amounts. If a best way to pay uses a coin , the other coins pay , and must do so with as few coins as possible: otherwise a better way to pay would give a better way to pay . So
the minimum running over the coins of the system that are at most .
"""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]")
$ 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]
best[6] came from best[3] , and last[6] records the coin ; the rebuild follows the recorded coins back from to to .The table has cells, and each looks at every coin: for coins, about steps. Trying all combinations of coins, as in chapter 18, took combinations for in Brenmoor; the table takes about 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 be the length of a longest common subsequence of the first letters of and the first of . If ’s letter and ’s letter are equal, one such subsequence ends with that letter, and . If they differ, at least one of them is not the last letter of the subsequence and can be dropped: . A row or a column with no letters holds . 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))
$ 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
LIBRARY and LITERARY share LIRARY, six letters.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. is the distance from the first elements of to the first of . In a best alignment, the last column either pairs ’s element with ’s element , for no cost if they are equal and otherwise; or holds ’s element over a gap, a deletion; or a gap over ’s element , an insertion. So is the smallest of (plus if the elements differ), and ; and , . 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]
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())
$ python align.py
distance in words: 3
the --- market opens at seven on sundays
||| |||||| ||||| || ***** || *******
the new market opens at eight on sunday
| 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 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 kilograms, it takes the object of kg worth and then nothing fits, when two objects of kg worth each give . Trying every subset is exact, but there are of them.
The subproblems use fewer objects and less room. Let be the best value with the first objects and at most kilograms. Object is left, and then ; or, if it fits, taken, and then the rest is the best load of 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)
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))
$ 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
The table has cells and each takes a few steps: for objects and kg, cells against subsets. The cost grows with , the size of the knapsack, not only with the number of objects: masses to the gram in a kg knapsack make 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,}")
$ 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
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.
: one computing call for each of , and a lookup for each of (the second call made by ). The naive version makes : for fib(5), for fib(4), and the call on itself.
Exercise 28.2 ★
Fill the table best for the coins , , up to the amount . Which coins pay ?
Solution
Solution of Exercise 28.2.
best for to : . For : , , ; the coin is recorded first, and .
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 letters: it comes after ST in STATION, and after N in NATIONS. The last cell of the table of the two words is , so none is longer.
Exercise 28.4 ★
In the knapsack table of the small case, from which cells is computed?
Solution
Solution of Exercise 28.4.
From (B left) and (B taken, leaving kg for A alone, which does not fit). The larger is .
Exercise 28.5 ★
Write binomial(n, k), memoised, from Pascal’s rule , with .
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 .
Exercise 28.6 ★★
A student memoises binomial with memo[n] instead of memo[(n, k)]. The call binomial_bad(10, 5) returns . Explain.
Solution
Solution of Exercise 28.6.
The result depends on both and , but the key records only . The first call on a row, say , stores its value in memo[7]; every later call on row , whatever its , returns that same value. The wrong values of the lower rows are added up the rows, and give instead of . 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 . Why?
Solution
Solution of Exercise 28.8.
Filling from the bottom right, the cell is computed before the cells , and it reads, which still hold their starting . Each cell sees only zeros, so it is if the letters are equal and otherwise; the last cell, Y with Y, gives . 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 squares, along its lines, moving only right or down? Set up a table.
Solution
Solution of Exercise 28.9.
Let be the number of paths to the crossing lines down and across. The first row and column hold ; a path to any other crossing arrives from above or from the left, so . The rows are Pascal’s triangle read diagonally, and , the number of ways to choose which of the 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 : k replaced by s, e by i, and g inserted.
Exercise 28.12 ★★★
Prove, by induction on , that change_table gives the fewest coins for every amount that can be paid.
Solution
Solution of Exercise 28.12.
Write for the fewest coins that pay . For , best[0] . Let 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 : a best way for , plus . So best[a] . Take a best way to pay and one of its coins : the others pay , with coins, so . The loop considers and finds best[a - c] + 1 . Hence best[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 random pairs.
Exercise 28.14 ★★★
Count the cells and the steps of knapsack for objects and a capacity . A removal van holds tonnes; its 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.
cells, each a comparison and an addition or two: the time and the memory grow like . In kilograms: cells, nothing for a computer. In grams: , about a gigabyte at 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 , not on how many digits it takes to write it. Adding three digits to 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 comparisons. For : .
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))
$ 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
Part I — The two versions.
- Read the two notices. List, in your own words, what the library changed.
- Why does the program compare words and not letters?
Sunday.andSundaycount as different words. Why? What would change if the program removed the punctuation first?
Part II — Common words.
- What does
lcs_table(a, b)[n][m]measure here? - How many words of the old version are not in the common subsequence? Of the new one?
- 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.
- Count the replacements, deletions and insertions in the printed columns. Check the distance.
- The deleted words
cents a day.come afterten -> nothing.. Give another alignment of the same cost for these words. - Why is
appointment -> appointment.a replacement? Thursdayandandare deleted. Write the columns of the alignment around them.- Each row of the distance table is filled from left to right. Which cells does need, and why is this order right?
- The rebuild starts at the bottom-right cell. Why does it never leave the table, and why does it stop?
- Prove that a column holding two different words in the rebuilt alignment costs one change, and that the total of the costs is .
Part IV — Memory.
- How many cells has the full table? How many bytes, at bytes per cell?
- Explain
distance_two_rows: what doesprevioushold at the start of each pass of the loop? - Why can the two-row version give the distance but not the alignment?
- Two versions of a book of words each: memory of the full table, and of two rows?
- Time: how many cells are computed in each version? Did saving memory cost time?
- The tests compare
distance_two_rowswith the full table on random pairs. Why is that a convincing check? - 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 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 : 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: .
5. of the old version, of the new one.
6. The kept columns of any alignment form a common subsequence, of at most words: at least old words are deleted or replaced, one operation each, so at least operations. Deleting the and inserting the always works: at most .
7. Replacements: nine, Sunday., four, ten, first, six,, appointment: . Deletions: cents, a, day., and, Thursday, only.: . Insertions: and, Monday.: . Total , 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. and , in the row above, filled during the previous pass; and , just to the left, filled earlier in the same pass. The first row and column are filled before the loops.
12. Each step lowers , or both by . A step that lowers is taken only with ; when the insertion test holds, since , and when the deletion test holds. So neither goes below , and the loop stops when both are , after at most 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 with two different words: one change. Along the path from to , the value drops by the cost of each column, and the costs add up to .
14. cells, bytes.
15. At the start of pass , previous is row : the distances from the first words of a to each beginning of b. The pass builds row in current, which becomes previous.
16. The rebuild walks back from the last cell through every row, and the earlier rows are gone.
17. cells, about gigabytes; two rows of cells, about megabytes.
18. Both compute the same cells; the saving costs no extra time.
19. The two programs are written differently, and they agree on 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 and words, share words in order and are word changes apart: replacements, deletions and insertions. The full table has cells; keeping two rows, cells give the same distance.