1 parent 1e0b33d commit 7a6ebb8Copy full SHA for 7a6ebb8
1 file changed
dynamic_programming/edit_distance.py
@@ -52,6 +52,35 @@ def solve(self, A, B):
52
53
return self.__solveDP(len(A)-1, len(B)-1)
54
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
84
if __name__ == '__main__':
85
try:
86
raw_input # Python 2
@@ -71,5 +100,10 @@ def solve(self, A, B):
100
101
print()
102
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)))
104
105
print("*************** End of Testing Edit Distance DP Algorithm ***************")
106
107
108
109
0 commit comments