Sub topic 5
Filling the Dynamic Programming Table
This chapter assumes you can read Python, work with 2D lists, and follow the recurrence from the previous chapter. In that recurrence, dp[i][j] is the edit distance between the first i characters of a and the first j characters of b. The task here is to compute every cell in an order that never reads a cell before it has been filled.
The shape of the table
For strings of lengths m and n, the table has m + 1 rows and n + 1 columns. The extra row and column stand for the empty prefix. They hold the base cases:
dp[i][0] = i, because turningicharacters into nothing takesideletions.dp[0][j] = j, because buildingjcharacters from nothing takesjinsertions.
Every other cell reads three neighbors: the cell above (delete), the cell to the left (insert), and the cell diagonally up and to the left (match or substitute).
Filling row by row, left to right, satisfies all three dependencies. Column by column also works, and so does sweeping anti-diagonals. A row-major loop is the simplest.
A worked example: "flaw" to "lawn"
Rows follow a = "flaw" and columns follow b = "lawn". The first row and the first column hold the base cases.
| Row | ε | l | a | w | n |
|---|---|---|---|---|---|
| ε | 0 | 1 | 2 | 3 | 4 |
| f | 1 | 1 | 2 | 3 | 4 |
| l | 2 | 1 | 2 | 3 | 4 |
| a | 3 | 2 | 1 | 2 | 3 |
| w | 4 | 3 | 2 | 1 | 2 |
Two cells show how the recurrence works:
dp[2][1]compares "fl" with "l". The characters match, so the diagonal givesdp[1][0] + 0 = 1. That beats the other two options, which give 2 and 3.dp[4][4]compares "flaw" with "lawn".wandndiffer. The options aredp[3][4] + 1 = 4,dp[4][3] + 1 = 2, anddp[3][3] + 1 = 3, so the minimum is 2. One script that achieves it is: deletef, keeplaw, insertn.
The answer always sits in the bottom-right cell, dp[m][n].
The implementation
def levenshtein(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
cost = 0 if a[i - 1] == b[j - 1] else 1
dp[i][j] = min(
dp[i - 1][j] + 1, # delete a[i-1]
dp[i][j - 1] + 1, # insert b[j-1]
dp[i - 1][j - 1] + cost, # match or substitute
)
return dp[m][n]
assert levenshtein("kitten", "sitting") == 3
assert levenshtein("", "abc") == 3
assert levenshtein("flaw", "lawn") == 2Common errors
- Off-by-one indexing. Cell
(i, j)covers prefixes of lengthiandj, so the last characters of those prefixes area[i - 1]andb[j - 1]. Writinga[i]either skips a character or raisesIndexError. - Missing base cases. If the first row and column stay at 0, the code computes something closer to a substring-matching score than edit distance.
- Wrong loop start. Starting the inner loops at 0 makes
dp[i - 1]wrap around to the last row through Python's negative indexing. Python raises no error, and the result is silently wrong.
Exercise
Fill the table for a = "cat" and b = "cut". What is dp[3][3], and which cell on the diagonal shows that the substitution happens?
Show answer
dp[3][3] = 1. The diagonal reads 0, 0, 1, 1. It goes up from 0 to 1 at dp[2][2], where 'a' and 'u' differ and the substitution costs 1. At dp[3][3] the 't' characters match, so the value carries over unchanged.
Exercise
A student writes dp = [[0] 4] 3 for two strings of lengths 2 and 3, then sets dp[i][0] = i for each row. What does dp[0][0] hold afterward, and why?
Show answer
It holds 2. All three rows are the same list object, so the last assignment, dp[2][0] = 2, overwrites column 0 in every row.