Sub topic 16
Edit Distance in Practice
This chapter assumes you know the Levenshtein recurrence, the two-row implementation, threshold-bounded computation, and the variants from earlier chapters: weighted costs, indel distance, Hamming distance, and optimal string alignment (OSA). The aim here is to choose the right variant for a real task and to combine it with the filtering that makes it fast enough to use.
Matching the Variant to the Task
Each application cares about a different kind of difference between strings. Choose the distance whose operations match the errors you expect to see.
| Application | Typical errors | Good choice | Why |
|---|---|---|---|
| Spell checking | Typos and swapped letters | OSA or Damerau-Levenshtein | A swap like "ie" to "ei" costs 1 instead of 2 |
| Fuzzy search over names | Missing or extra characters | Levenshtein with a threshold k | The band limits work to O(k·n) per candidate |
| Line-based diff | Lines added or removed | Indel distance (LCS) | A changed line is a delete plus an insert |
| Fixed-length codes, checksums | Flipped symbols | Hamming | Lengths are equal and no shifts occur |
| DNA and protein alignment | Mutations, gaps | Weighted costs, often with affine gap penalties | Some substitutions are more likely than others |
Tools like diff and git diff use Myers' O((n+m)·D) diff algorithm. It is fast when the number of differences D is small, which is the usual case for two versions of a file. Bioinformatics tools build on the same table under other names. Needleman-Wunsch is global alignment with a scoring matrix. Smith-Waterman finds the best local alignment by letting a score reset to zero.
A Spell-Check Pipeline
Comparing a word against every dictionary entry with a full table costs too much on large vocabularies. Practical systems first filter candidates cheaply, then run a bounded distance on the survivors, then rank them.
The code below runs the bounded-distance and ranking stages. A length check stands in for the filter.
def bounded_levenshtein(a, b, k):
if abs(len(a) - len(b)) > k:
return None
prev = list(range(len(b) + 1))
for i, ca in enumerate(a, 1):
curr = [i]
for j, cb in enumerate(b, 1):
curr.append(min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + (ca != cb)))
if min(curr) > k:
return None # row minimum never decreases, so stop early
prev = curr
return prev[-1] if prev[-1] <= k else None
def suggest(word, dictionary, k=2):
scored = []
for w in dictionary:
d = bounded_levenshtein(word, w, k)
if d is not None:
scored.append((d, w))
return [w for d, w in sorted(scored)]
words = ["receive", "recipe", "relieve", "deceive", "receiver", "race"]
print(suggest("recieve", words)) # ['relieve', 'receive', 'recipe']Plain Levenshtein ranks "relieve" (distance 1) above "receive" (distance 2), which is probably the word the user meant. Under OSA the swap costs 1, so "receive" ties for first place, and a word-frequency tiebreak would then pick it.
Common Mistakes
- Comparing raw distances across strings of very different lengths. A distance of 3 is small for a 40-character address and large for a 4-letter word. Divide by
max(len(a), len(b))when you need a similarity score. - Ignoring normalization. Lowercasing, Unicode normalization (NFC), and trimming whitespace often fix more mismatches than a better distance function does.
- Treating Python strings as characters people see. An accented letter in NFD form is two code points, so it counts as two edits.
Exercise
You are building autocomplete for a product catalog of 2 million names, and you want matches within 2 typos. Which distance would you use, how would you avoid computing it 2 million times per keystroke, and why should you not use OSA with a BK-tree?
Show answer
Use Levenshtein (or unrestricted Damerau-Levenshtein if swaps are common) with threshold k = 2, so each comparison runs in a band and stops early. Index the catalog with a BK-tree, or filter with n-grams or length first, so only a small candidate set reaches the distance check. OSA violates the triangle inequality, and BK-tree pruning relies on that inequality, so it could wrongly discard valid matches.
Exercise
Why does line-based diff use indel distance rather than Levenshtein with substitutions?
Show answer
A changed line is shown as one line removed and one line added. Indel distance models exactly that, and it maps directly onto the longest common subsequence of lines, which is the set of unchanged lines that diff keeps.