150 XP

34. Edit distance

Expert dynamic programming strings

Write a function edit_distance(a, b) that takes two words and returns the smallest number of edits that turn a into b, as a whole number. Each edit is one of these:

  • insert one letter, anywhere in the word;
  • delete one letter;
  • replace one letter with a different letter.

This number is also called the Levenshtein distance. If the two words are the same, it is 0. If one word is empty, it is the length of the other: you insert (or delete) every letter.

Example 1

Inputa = "kitten", b = "sitting"
Output3
ExplanationReplace k with s, e with i, then insert g.

Example 2

Inputa = "flaw", b = "lawn"
Output2
ExplanationDelete the f, then add n at the end.

Example 3

Inputa = "horse", b = "ros"
Output3
ExplanationReplace h with r, delete r, delete e.

Constraints

  • a and b each have 0 to 100 letters, all lower case.

Submit also runs 6 more tests you can't see.

Code
def edit_distance(a, b):
    """Fewest single-letter edits that turn a into b.

    a, b: str, lower-case words; either may be empty
    Returns: int, the smallest number of inserts, deletes
        and replacements
    """
    # Write your code here
    pass