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

Method min_dist_bottom_up

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

>>> EditDistance().min_dist_bottom_up("intention", "execution") 5 >>> EditDistance().min_dist_bottom_up("intention", "") 9 >>> EditDistance().min_dist_bottom_up("", "") 0

(self, word1: str, word2: str)

Source from the content-addressed store, hash-verified

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)
72 self.dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
73
74 for i in range(m + 1):
75 for j in range(n + 1):
76 if i == 0: # first string is empty
77 self.dp[i][j] = j
78 elif j == 0: # second string is empty
79 self.dp[i][j] = i
80 elif word1[i - 1] == word2[j - 1]: # last characters are equal
81 self.dp[i][j] = self.dp[i - 1][j - 1]
82 else:
83 insert = self.dp[i][j - 1]
84 delete = self.dp[i - 1][j]
85 replace = self.dp[i - 1][j - 1]
86 self.dp[i][j] = 1 + min(insert, delete, replace)
87 return self.dp[m][n]
88
89
90if __name__ == "__main__":

Callers 1

edit_distance.pyFile · 0.80

Calls

no outgoing calls

Tested by

no test coverage detected