12/40
Part 3 of 7 · Two sequencesLearn and do
A table over two sequences
Here is a question about two strings at once.
tails.
Edit distance is the fewest single-letter edits that turn one string into another. An edit inserts a letter, deletes one, or swaps one letter for another. tails becomes train in 3, as above. Spell checkers rank suggestions by it, and diff and DNA alignment are its relatives.
The state is a pair of positions, one in each string. So the table has a row for each prefix of one string and a column for each prefix of the other.
- The cell.
d[i][j]is the edit distance froma[:i], the firstiletters ofa, tob[:j]. - The recurrence. Look at the last letters,
a[i - 1]andb[j - 1]. If they're equal, keep them:d[i][j] = d[i - 1][j - 1]. If not, the last edit was one of three, and each one is a neighbor of the cell. Sod[i][j] = 1 + min(diagonal, above, left). - The base cases.
d[i][0] = i, deleting every letter, andd[0][j] = j, inserting every letter. - The order. Row by row, left to right. Above, left and the diagonal are all filled first.
Here is what each neighbor stands for:
| The cell read | The last edit it stands for |
|---|---|
d[i-1][j-1], the diagonal | swap a[i-1] for b[j-1], or keep it if they match |
d[i-1][j], above | delete a[i-1] |
d[i][j-1], to the left | insert b[j-1] |
- The diagonal used one letter fewer of both strings, so the last step dealt with both last letters together.
- The cell above used one letter fewer of
a, so the last step dealt witha[i - 1]alone. - The cell to the left used one letter fewer of
b, so the last step dealt withb[j - 1]alone.
In the editor, write edit_distance(a, b) from the four things. It prints the table for tails and train, then three edges.