Skip to content

Instantly share code, notes, and snippets.

@macroxela
Created May 11, 2020 08:01
Show Gist options
  • Save macroxela/720b4bb2601a167b035bf2f3ca968f25 to your computer and use it in GitHub Desktop.
Save macroxela/720b4bb2601a167b035bf2f3ca968f25 to your computer and use it in GitHub Desktop.
Dynamic Programming solution to edit distance problem
######################################################################################################################
# Edit Distance
# Find the minimum number of operations (replace, delete, insert) to convert string a to string b. Uses a bottom up
# dynamic programming approach. Based on example from YouTube channel 'Back to Back SWE': https://www.youtube.com/watch?v=MiqoA-yF-0M
#
# replace delete insert
# Recursive Equation: ED(a, b) = min( ED(a-1, b-1), ED(a-1, b), ED(a, b-1) ) where a-1 means removing 1 character from string a
#
######################################################################################################################
def EditDistance(astring, bstring):
#Initialize matrix values
matrix = [[0 for i in range(0, len(astring)+1)] for j in range(0, len(bstring)+1)]
#For the empty string, number of operations will always be equal to number of characters
for i in range(len(astring)+1): matrix[0][i] = i
for i in range(len(bstring)+1): matrix[i][0] = i
#Bottom up dynamic programming
for i in range(1, len(bstring)+1):
for j in range(1, len(astring)+1):
#If same character there should be no change
if bstring[i-1] == astring[j-1]:
matrix[i][j] = matrix[i-1][j-1]
#Takes minimum of replace [i-1][j-1], delete[i-1][j], or insert [i][j-1] and adds the current character
else:
matrix[i][j] = min(matrix[i-1][j-1], matrix[i-1][j], matrix[i][j-1])+1
return matrix[len(bstring)][len(astring)]
def printMat(matrix):
for i in matrix:
print(i)
a = "benyam"
b = "ephrem"
ans = EditDistance(a, b)
print(ans)
a = "string"
b = "bring"
ans = EditDistance(a, b)
print(ans)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment