34. Edit distance
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
a = "kitten", b = "sitting"3Example 2
a = "flaw", b = "lawn"2Example 3
a = "horse", b = "ros"3Constraints
aandbeach have 0 to 100 letters, all lower case.
Submit also runs 6 more tests you can't see.
- Solve smaller versions first: let
d[i][j]be the distance between the firstiletters ofaand the firstjletters ofb. The answer isd[len(a)][len(b)]. - The edges of the table are easy: turning
iletters into the empty word takesideletes, sod[i][0] = i, and likewised[0][j] = jinserts. That also answers an emptyaorb. - For every other cell, the last edit was a delete (
d[i - 1][j] + 1), an insert (d[i][j - 1] + 1) or a replace (d[i - 1][j - 1], plus 1 only whena[i - 1] != b[j - 1]). Take the smallest of the three.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.