Compute Levenshtein edit distance
Spell checkers, fuzzy matching and word error rate for speech models all use edit distance: the fewest single-character inserts, deletes and substitutions to turn one string into another.
Write edit_distance(a, b) with dynamic programming. Each operation costs 1.
def edit_distance(a, b)Understand the idea
Edit distance counts the fewest single-character inserts, deletes and substitutions needed to turn one string into another. Comparing position by position fails as soon as one character is inserted, because everything after it shifts. Dynamic programming fixes this: build a table where D[i][j] is the distance between the first i characters of a and the first j of b, and fill it from smaller prefixes. Worked example: a = 'cat', b = 'cart'. Position by position, 't' vs 'r' and then a missing letter look like 2 changes, but the true answer is 1: insert 'r'. Small table for 'ab' to 'b': D[0][j] = j and D[i][0] = i. D[1][1] ('a' vs 'b') = 1. D[2][1] ('ab' vs 'b'): last characters match, so D[1][0] = 1. Answer 1 (delete 'a'). Rule: D[i][j] = min(D[i-1][j] + 1, D[i][j-1] + 1, D[i-1][j-1] + (0 if a_i == b_j else 1)). Spell checkers and word error rate for speech models use this.