The problem
An edit is one of three changes to a string: insert a letter anywhere, delete a letter, or replace a letter with another. Return the fewest edits that turn a into b. This number is the edit distance (also called the Levenshtein distance).
edit_distance("kitten", "sitting") # 3
# k -> s, e -> i, insert g
edit_distance("horse", "ros") # 3
edit_distance("", "abc") # 3
Limits
- Each string has up to 1,000 letters. Aim for O(len(a) × len(b)).
- Python stops at about 1,000 nested calls, and a function wrapped in
functools.cachestops after a few hundred in the browser. The big tests need far more than that, so memoised recursion fails them. Fill a table with a loop (lesson 3).
Builds on DYNP-7 LCS and edit distance.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
10 tests, not run yet
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The example | Not run | |
| 2 | From nothing | Not run | |
| 3 | To nothing | Not run | |
| 4 | The same | Not run | |
| 5 | Horse to ros | Not run | |
| 6 | Intention to execution | Not run | |
| 7 | Shifted by one | Not run | |
| 8 | Nothing in common, 14 letters | Not run | |
| 9 | 1,000 letters each | Not run | |
| 10 | Different lengths | Not run |