DYNP-P7

Edit distance

Practice 7 of 9Dynamic programming10 tests

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.cache stops 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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

10 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2From nothingNot run
3To nothingNot run
4The sameNot run
5Horse to rosNot run
6Intention to executionNot run
7Shifted by oneNot run
8Nothing in common, 14 lettersNot run
91,000 letters eachNot run
10Different lengthsNot run