Skip to content

Commit 7a6ebb8

Browse files
SandersLincclauss
authored andcommitted
Update edit_distance.py (TheAlgorithms#1001)
added bottom up method.
1 parent 1e0b33d commit 7a6ebb8

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

dynamic_programming/edit_distance.py

+34
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,35 @@ def solve(self, A, B):
5252

5353
return self.__solveDP(len(A)-1, len(B)-1)
5454

55+
56+
def min_distance_bottom_up(word1: str, word2: str) -> int:
57+
"""
58+
>>> min_distance_bottom_up("intention", "execution")
59+
5
60+
>>> min_distance_bottom_up("intention", "")
61+
9
62+
>>> min_distance_bottom_up("", "")
63+
0
64+
"""
65+
m = len(word1)
66+
n = len(word2)
67+
dp = [[0 for _ in range(n+1) ] for _ in range(m+1)]
68+
for i in range(m+1):
69+
for j in range(n+1):
70+
71+
if i == 0: #first string is empty
72+
dp[i][j] = j
73+
elif j == 0: #second string is empty
74+
dp[i][j] = i
75+
elif word1[i-1] == word2[j-1]: #last character of both substing is equal
76+
dp[i][j] = dp[i-1][j-1]
77+
else:
78+
insert = dp[i][j-1]
79+
delete = dp[i-1][j]
80+
replace = dp[i-1][j-1]
81+
dp[i][j] = 1 + min(insert, delete, replace)
82+
return dp[m][n]
83+
5584
if __name__ == '__main__':
5685
try:
5786
raw_input # Python 2
@@ -71,5 +100,10 @@ def solve(self, A, B):
71100

72101
print()
73102
print("The minimum Edit Distance is: %d" % (solver.solve(S1, S2)))
103+
print("The minimum Edit Distance is: %d" % (min_distance_bottom_up(S1, S2)))
74104
print()
75105
print("*************** End of Testing Edit Distance DP Algorithm ***************")
106+
107+
108+
109+

0 commit comments

Comments
 (0)