

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Edit Distance
incomplete
2: Slow Edit Distance
incomplete
3: Edit Distance
incomplete
4: Dynamic Programming Edit Distance
incomplete
5: Fast Edit Distance – Review
incomplete
6: Memoization vs. Tabulation – Review
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Let's see if edit distance is a dynamic programming problem. We need to answer the two qualifying questions:
In order to answer that, let's take a look at the naïve implementation.
def edit_distance(str1: str, str2: str) -> int:
# 1st string is empty; distance is length of 2nd string
if str1 == "":
return len(str2)
# 2nd string is empty; distance is length of 1st string
if str2 == "":
return len(str1)
# last character in strings is the same;
# distance is the same as the strings excluding
# their last letters
if str1[-1] == str2[-1]:
return edit_distance(str1[:-1], str2[:-1])
# last characters vary; distance is one more than
# the smallest distance among the insert, delete, and
# substitute operations
return (
1
+ min(
edit_distance(str1, str2[:-1]), # insert
edit_distance(str1[:-1], str2), # delete
edit_distance(str1[:-1], str2[:-1]), # substitute
)
)