Skip to content

Update edit_distance.py #1001

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 13, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions dynamic_programming/edit_distance.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,35 @@ def solve(self, A, B):

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


def min_distance_bottom_up(word1: str, word2: str) -> int:
"""
>>> min_distance_bottom_up("intention", "execution")
5
>>> min_distance_bottom_up("intention", "")
9
>>> min_distance_bottom_up("", "")
0
"""
m = len(word1)
n = len(word2)
dp = [[0 for _ in range(n+1) ] for _ in range(m+1)]
for i in range(m+1):
for j in range(n+1):

if i == 0: #first string is empty
dp[i][j] = j
elif j == 0: #second string is empty
dp[i][j] = i
elif word1[i-1] == word2[j-1]: #last character of both substing is equal
dp[i][j] = dp[i-1][j-1]
else:
insert = dp[i][j-1]
delete = dp[i-1][j]
replace = dp[i-1][j-1]
dp[i][j] = 1 + min(insert, delete, replace)
return dp[m][n]

if __name__ == '__main__':
try:
raw_input # Python 2
Expand All @@ -71,5 +100,10 @@ def solve(self, A, B):

print()
print("The minimum Edit Distance is: %d" % (solver.solve(S1, S2)))
print("The minimum Edit Distance is: %d" % (min_distance_bottom_up(S1, S2)))
print()
print("*************** End of Testing Edit Distance DP Algorithm ***************")