Sub topic 2
Defining Levenshtein Distance
This chapter assumes you can read basic Python, work with strings and lists, and know the three edit operations from the previous chapter: insertion, deletion, and substitution. In this chapter we turn those operations into a precise measure.
The Definition
The Levenshtein distance between strings a and b, written d(a, b), is the smallest number of single-character insertions, deletions, and substitutions that turn a into b. Each operation costs 1.
The word that matters most is smallest. Many edit sequences can turn a into b. For example, you can always delete every character of a and then insert every character of b. The distance is the length of the shortest such sequence, not of any sequence you happen to find.
The classic example is kitten to sitting:
The sequence has three operations, and no shorter one exists, so d("kitten", "sitting") = 3.
Checking an Edit Sequence in Code
The function below applies a list of edits to a string. It can show that a sequence is valid, meaning it produces the target. It cannot show that the sequence is minimal.
def apply_edits(s, ops):
chars = list(s)
for op in ops:
kind = op[0]
if kind == "sub":
_, i, c = op
chars[i] = c
elif kind == "ins":
_, i, c = op
chars.insert(i, c)
elif kind == "del":
_, i = op
del chars[i]
else:
raise ValueError(f"unknown operation: {kind}")
return "".join(chars)
ops = [("sub", 0, "s"), ("sub", 4, "i"), ("ins", 6, "g")]
assert apply_edits("kitten", ops) == "sitting"
print(len(ops)) # 3: an upper bound on the distanceEach valid sequence you find gives an upper bound on the distance. To prove it is the lowest possible, you have to rule out every shorter sequence. The recurrence and the dynamic programming table in the next chapters do exactly that.
Bounds You Can State Without Computing
For strings of lengths m and n, some facts follow directly from the definition:
| Property | Statement | Reason | Column | Column |
|---|---|---|---|---|
| Identity | `d(a, b) = 0` exactly when `a == b` | Only equal strings need zero edits | ||
| Symmetry | `d(a, b) = d(b, a)` | Swap each insertion with a deletion; substitutions reverse | ||
| Lower bound | `d(a, b) ≥ \ | m − n\ | ` | Each insertion or deletion changes the length by at most 1 |
| Upper bound | `d(a, b) ≤ max(m, n)` | Substitute the overlapping `min(m, n)` positions, then insert or delete the remaining characters | ||
| Empty string | `d("", b) = n` | Only insertions are possible |
You can use these bounds to sanity-check results. If your code returns 7 for two strings of length 5, the code has a bug.
Common Mistakes
- Counting a substitution for matching characters. Keeping a character that already matches costs 0. A substitution counts only when the characters differ.
- Comparing by position. Lining up
abcdefagainstbcdefaindex by index makes every position differ, but the distance is 2: delete the leadinga, then appendaat the end. Insertions and deletions shift everything after them. - Assuming a swap costs 1. Standard Levenshtein has no transposition operation, so
abtobacosts 2. A later chapter covers variants that allow swaps. - Treating a found sequence as optimal. A greedy left-to-right edit plan often gives a sequence longer than necessary.
Exercises
Exercise
Find d("flaw", "lawn") and give one edit sequence that achieves it.
Show answer
The distance is 2. Delete the leading "f" to get "law", then insert "n" at the end to get "lawn". The distance cannot be 1, because a single edit either keeps the length at 4 (one substitution, but "flaw" and "lawn" differ in all four positions) or changes it to 3 or 5.
Exercise
Without running any algorithm, give the bounds on d("abc", "wxyz"), then find the exact value.
Show answer
The bounds are |3 − 4| = 1 ≤ d ≤ max(3, 4) = 4. The two strings share no characters, so no position can be kept for free. Each of the 4 characters of "wxyz" must come from a substitution or an insertion, so d = 4.