Sub topic 1
Turning One String into Another: The Three Edit Operations
Prerequisites
This chapter assumes you can write basic Python, work with strings and 2D lists, read Big-O notation, and follow a recursive definition. Some familiarity with memoization or dynamic programming helps.
The Three Edit Operations
An edit operation changes a string by one character:
| Operation | Example | Effect |
|---|---|---|
| Insertion | `cat` → `cart` | add one character |
| Deletion | `cart` → `cat` | remove one character |
| Substitution | `cat` → `cut` | replace one character |
Defining Levenshtein Distance
The Levenshtein distance between strings a and b is the minimum number of insertions, deletions, and substitutions that turn a into b. For example, kitten → sitting takes 3 edits: substitute k→s, substitute e→i, and insert g. No sequence of 2 edits does it.
A common mistake is to count any working sequence of edits. The distance is the minimum over all sequences, so you need an algorithm that searches them efficiently.
A Simpler Cousin: Hamming Distance
Hamming distance allows only substitutions, so it is defined only for strings of equal length. It counts the positions where the two strings differ.
def hamming(a, b):
if len(a) != len(b):
raise ValueError("Hamming distance requires equal-length strings")
return sum(x != y for x, y in zip(a, b))
assert hamming("karolin", "kathrin") == 3Building the Recurrence from Prefixes
Let D(i, j) be the distance between the first i characters of a and the first j characters of b. The base cases are D(i, 0) = i, which takes i deletions, and D(0, j) = j, which takes j insertions. Otherwise, the last step of an optimal edit sequence is one of three moves:
D(i-1, j) + 1: deletea[i-1]D(i, j-1) + 1: insertb[j-1]D(i-1, j-1) + cost: match the last characters (cost 0 if they are equal) or substitute them (cost 1)
D(i, j) is the minimum of these three values.
Filling the Dynamic Programming Table
A plain recursive implementation recomputes the same subproblems over and over. A table of size (m+1) by (n+1), filled row by row, computes each cell once.
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") == 3Exercise
Fill the table for a = "ab" and b = "b". What is the distance, and which edit achieves it?
Show answer
Row 0 is [0, 1]. Row 1 ("a") is [1, 1]. Row 2 ("ab") is [2, 1]. The distance is 1: delete "a".