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.

Signaturedef 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.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: kitten to sittingedit_distance('kitten', 'sitting')
  • Sample 2: insertion at frontedit_distance('token', 'tokens') + edit_distance('pre', 'xpre')
  • Test 3: emptyedit_distance('', 'abc')
  • Test 4: sameedit_distance('llm', 'llm')