MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / EditDistance

Class EditDistance

dynamic_programming/edit_distance.py:14–87  ·  view source on GitHub ↗

Use : solver = EditDistance() editDistanceResult = solver.solve(firstString, secondString)

Source from the content-addressed store, hash-verified

12
13
14class EditDistance:
15 """
16 Use :
17 solver = EditDistance()
18 editDistanceResult = solver.solve(firstString, secondString)
19 """
20
21 def __init__(self):
22 self.word1 = ""
23 self.word2 = ""
24 self.dp = []
25
26 def __min_dist_top_down_dp(self, m: int, n: int) -> int:
27 if m == -1:
28 return n + 1
29 elif n == -1:
30 return m + 1
31 elif self.dp[m][n] > -1:
32 return self.dp[m][n]
33 else:
34 if self.word1[m] == self.word2[n]:
35 self.dp[m][n] = self.__min_dist_top_down_dp(m - 1, n - 1)
36 else:
37 insert = self.__min_dist_top_down_dp(m, n - 1)
38 delete = self.__min_dist_top_down_dp(m - 1, n)
39 replace = self.__min_dist_top_down_dp(m - 1, n - 1)
40 self.dp[m][n] = 1 + min(insert, delete, replace)
41
42 return self.dp[m][n]
43
44 def min_dist_top_down(self, word1: str, word2: str) -> int:
45 """
46 >>> EditDistance().min_dist_top_down("intention", "execution")
47 5
48 >>> EditDistance().min_dist_top_down("intention", "")
49 9
50 >>> EditDistance().min_dist_top_down("", "")
51 0
52 """
53 self.word1 = word1
54 self.word2 = word2
55 self.dp = [[-1 for _ in range(len(word2))] for _ in range(len(word1))]
56
57 return self.__min_dist_top_down_dp(len(word1) - 1, len(word2) - 1)
58
59 def min_dist_bottom_up(self, word1: str, word2: str) -> int:
60 """
61 >>> EditDistance().min_dist_bottom_up("intention", "execution")
62 5
63 >>> EditDistance().min_dist_bottom_up("intention", "")
64 9
65 >>> EditDistance().min_dist_bottom_up("", "")
66 0
67 """
68 self.word1 = word1
69 self.word2 = word2
70 m = len(word1)
71 n = len(word2)

Callers 1

edit_distance.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected