-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1 from sjg21010/Implementation
Implementation-Merge-1
- Loading branch information
Showing
1 changed file
with
24 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
def edit_distance(str1, str2): #input is 2 strings that we will be comparing | ||
|
||
# create a matrix that has length str2 + 1 columns and length str1 + 1 rows | ||
D = [[0 for i in range(len(str2)+1)] for j in range(len(str1)+1)] | ||
|
||
#initialize first row - how many deletions are needed to get an empty list | ||
for i in range(len(str1)+1): | ||
D[i][0] = i | ||
|
||
#initialize first column - how many insertions to go from empty list to str2 | ||
for j in range(len(str2)+1): | ||
D[0][j] = j | ||
|
||
#fill in rest of matrix with recursive case | ||
for i in range(1, len(str1)+1): | ||
for j in range(1, len(str2)+1): | ||
if str1[i-1] == str2[j-1]: | ||
cost = 0 #match: no operation needed | ||
else: | ||
cost = 1 #no match: substitution | ||
D[i][j] = min(D[i-1][j] + 1, D[i][j-1] + 1,D[i-1][j-1] + cost) | ||
|
||
return D[len(str1)][len(str2)] #last cell of matrix contains optimal solution | ||
|