Edit distance
🌍 In real life. You type "fone" on your phone, and the keyboard offers "fine", "one" and "phone". To choose, a spell-checker measures how far the typed word is from each dictionary word: the fewest single-letter edits that turn one into the other. "fine" is 1 edit away (o becomes i); "phone" is 2 (f becomes h, and p goes in front).
The idea in one sentence: the edit distance dp[i][j] between the first i letters of a and the first j of b comes from the last letters: if they agree they cost nothing, and if not, the last edit was a replace, a delete or an insert, so take 1 plus the cheapest of those three cells.
Its words:
- edit: insert one letter, delete one letter, or replace one letter with another
- edit distance (Levenshtein distance): the fewest edits from
atob - row 0 and column 0: from nothing to j letters takes j inserts; from i letters to nothing takes i deletes
Step by step:
- make a
(m + 1) × (n + 1)table;dp[0][j] = janddp[i][0] = i - if
a[i − 1] == b[j − 1]:dp[i][j] = dp[i − 1][j − 1] - otherwise
dp[i][j] = 1 + min(dp[i − 1][j − 1], dp[i − 1][j], dp[i][j − 1]): replace, delete, insert - the answer is
dp[m][n]; walking back reads off the edits
Watch FONE become PHONE in 2 edits:
Why the three neighbours cover every case. Line up the edits that turn a[:i] into b[:j] and look at what happens to the two last letters. Either a[i − 1] becomes b[j − 1] (free if they agree, a replace if not: the cell up-left), or a[i − 1] is deleted (the rest of a[:i − 1] still has to become b[:j]: the cell above), or b[j − 1] is inserted at the end (a[:i] still has to become b[:j − 1]: the cell to the left). Nothing else can happen to them, so the smallest of the three is the answer.
What it costs, by counting. (m + 1) × (n + 1) cells, three lookups each. A spell-checker comparing an 8-letter word with 100,000 dictionary words of about 8 letters fills about 100,000 × 9 × 9 = 100,000 × 81, roughly 8,100,000 cells; real keyboards skip words that differ too much in length to cut that down. In Big-O: O(m × n) time and memory for words of lengths m and n.
def edit_distance(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)] # dp[i][j]: the fewest edits from a[:i] to b[:j]
for i in range(m + 1):
dp[i][0] = i # delete all i letters
for j in range(n + 1):
dp[0][j] = j # insert all j letters
for i in range(1, m + 1):
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]:
dp[i][j] = dp[i - 1][j - 1] # the last letters agree: no edit
else:
dp[i][j] = 1 + min(dp[i - 1][j - 1], # replace a's last letter with b's
dp[i - 1][j], # delete a's last letter
dp[i][j - 1]) # insert b's last letter
return dp[m][n]
def closest_word(typed, words):
best = words[0]
for w in words[1:]:
if edit_distance(typed, w) < edit_distance(typed, best): # a tie keeps the earlier word
best = w
return best
print(edit_distance("FONE", "PHONE"), edit_distance("kitten", "sitting"))
print(closest_word("fone", ["phone", "fine", "one"]))Mistakes and edge cases.
- forgetting row 0 and column 0: leaving them 0 says "abc" turns into "" for free
- adding 1 when the letters agree: a matching pair costs nothing, so copy the cell up-left
- counting differences position by position: "fone" and "phone" differ in every position once lined up from the left, yet only 2 edits are needed
- an empty word: the distance is simply the other word's length
- LCS is related: with only inserts and deletes allowed, the distance is
m + n − 2 × LCS(Lesson 58.2)
Quiz
What does this print?
def edit_distance(a, b): m, n = len(a), len(b) dp = [[0] * (n + 1) for _ in range(m + 1)] # dp[i][j]: the fewest edits from a[:i] to b[:j] for i in range(m + 1): dp[i][0] = i # delete all i letters for j in range(n + 1): dp[0][j] = j # insert all j letters for i in range(1, m + 1): for j in range(1, n + 1): if a[i - 1] == b[j - 1]: dp[i][j] = dp[i - 1][j - 1] # the last letters agree: no edit else: dp[i][j] = 1 + min(dp[i - 1][j - 1], # replace a's last letter with b's dp[i - 1][j], # delete a's last letter dp[i][j - 1]) # insert b's last letter return dp[m][n] print(edit_distance("horse", "ros"))Which cell does a delete of a[i − 1] come from?
- dp[i − 1][j], the cell above
- dp[i][j − 1], the cell to the left
- dp[i − 1][j − 1], up and left
What does this print?
def edit_distance(a, b): m, n = len(a), len(b) dp = [[0] * (n + 1) for _ in range(m + 1)] # dp[i][j]: the fewest edits from a[:i] to b[:j] for i in range(m + 1): dp[i][0] = i # delete all i letters for j in range(n + 1): dp[0][j] = j # insert all j letters for i in range(1, m + 1): for j in range(1, n + 1): if a[i - 1] == b[j - 1]: dp[i][j] = dp[i - 1][j - 1] # the last letters agree: no edit else: dp[i][j] = 1 + min(dp[i - 1][j - 1], # replace a's last letter with b's dp[i - 1][j], # delete a's last letter dp[i][j - 1]) # insert b's last letter return dp[m][n] print(edit_distance("", "cat"), edit_distance("cat", "cat"))With only inserts and deletes, how far apart are CODE and COLD (their LCS is COD)?
- 2: delete E, insert L
- 1
- 4
edit_distance("abc", "") gives 0 instead of 3. Which line is wrong?
def edit_distance(a, b): m, n = len(a), len(b) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(m): 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): if a[i - 1] == b[j - 1]: dp[i][j] = dp[i - 1][j - 1] else: dp[i][j] = 1 + min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) return dp[m][n]
Coding tasks
Write
edit_distance(a, b): the fewest single-letter inserts, deletes and replaces that turnaintob.Write
closest_word(typed, words): return the word inwordswith the smallest edit distance fromtyped; on a tie, the one that comes first inwords. Writeedit_distancein your answer too.