|
| 1 | +""" |
| 2 | +Author : Turfa Auliarachman |
| 3 | +Date : October 12, 2016 |
| 4 | +
|
| 5 | +This is a pure Python implementation of Dynamic Programming solution to the edit distance problem. |
| 6 | +
|
| 7 | +The problem is : |
| 8 | +Given two strings A and B. Find the minimum number of operations to string B such that A = B. The permitted operations are removal, insertion, and substitution. |
| 9 | +""" |
| 10 | + |
| 11 | +class EditDistance: |
| 12 | + """ |
| 13 | + Use : |
| 14 | + solver = EditDistance() |
| 15 | + editDistanceResult = solver.solve(firstString, secondString) |
| 16 | + """ |
| 17 | + |
| 18 | + def __init__(self): |
| 19 | + self.__prepare__() |
| 20 | + |
| 21 | + def __prepare__(self, N = 0, M = 0): |
| 22 | + self.dp = [[-1 for y in range(0,M)] for x in range(0,N)] |
| 23 | + |
| 24 | + def __solveDP(self, x, y): |
| 25 | + if (x==-1): |
| 26 | + return y+1 |
| 27 | + elif (y==-1): |
| 28 | + return x+1 |
| 29 | + elif (self.dp[x][y]>-1): |
| 30 | + return self.dp[x][y] |
| 31 | + else: |
| 32 | + if (self.A[x]==self.B[y]): |
| 33 | + self.dp[x][y] = self.__solveDP(x-1,y-1) |
| 34 | + else: |
| 35 | + self.dp[x][y] = 1+min(self.__solveDP(x,y-1), self.__solveDP(x-1,y), self.__solveDP(x-1,y-1)) |
| 36 | + |
| 37 | + return self.dp[x][y] |
| 38 | + |
| 39 | + def solve(self, A, B): |
| 40 | + if isinstance(A,bytes): |
| 41 | + A = A.decode('ascii') |
| 42 | + |
| 43 | + if isinstance(B,bytes): |
| 44 | + B = B.decode('ascii') |
| 45 | + |
| 46 | + self.A = str(A) |
| 47 | + self.B = str(B) |
| 48 | + |
| 49 | + self.__prepare__(len(A), len(B)) |
| 50 | + |
| 51 | + return self.__solveDP(len(A)-1, len(B)-1) |
| 52 | + |
| 53 | +if __name__ == '__main__': |
| 54 | + import sys |
| 55 | + if sys.version_info.major < 3: |
| 56 | + input_function = raw_input |
| 57 | + else: |
| 58 | + input_function = input |
| 59 | + |
| 60 | + solver = EditDistance() |
| 61 | + |
| 62 | + print("****************** Testing Edit Distance DP Algorithm ******************") |
| 63 | + print() |
| 64 | + |
| 65 | + print("Enter the first string: ", end="") |
| 66 | + S1 = input_function() |
| 67 | + |
| 68 | + print("Enter the second string: ", end="") |
| 69 | + S2 = input_function() |
| 70 | + |
| 71 | + print() |
| 72 | + print("The minimum Edit Distance is: %d" % (solver.solve(S1, S2))) |
| 73 | + print() |
| 74 | + print("*************** End of Testing Edit Distance DP Algorithm ***************") |
0 commit comments