Python program to find Edit Distance between two stringsThe edit distance between two strings measures the minimum number of operations that are needed to convert one string into another. There are various operations that may be performed, including insertion, deletion, and substitution of a single character. The edit distance is also referred to as the Levenshtein distance or the minimum edit distance. An algorithm to find the edit distance between two strings:
Python code to implement this algorithm: Output: 3 8 Explanation: In the first example, the edit distance between "kitten" and "sitting" is 3. We can transform "kitten" into "sitting" by substituting "k" with "s", substituting "e" with "i", and inserting "g" at the end. In the second example, the edit distance between "rosettacode" and "raisethysword" is 8. We can transform "rosettacode" into "raisethysword" by deleting "o", substituting "c" with "i", substituting "d" with "s", substituting "e" with "t", inserting "h" after "t", Time Complexity:
Therefore, the overall time complexity of the function edit_distance() is O(mn). Space Complexity:
Therefore, the space complexity of the function edit_distance() is O(mn). There are other approaches to calculating the edit distance between two strings in Python. Here are a few:
For Example: Output: 3
For Example: Output: 3
For Example: Output: 3 Note: The NumPy approach is similar to the first approach in terms of time and space complexity, but it provides an efficient way to perform the matrix operations using the built-in functions of the NumPy library.
In dynamic programming, we create a matrix where each cell represents the edit distance between two substrings. We start by initializing the first row and column with incremental values from 0 to n, where n is the length of the string. After that, we iterate over the remaining cells in the matrix and fill them using the following formula: The final answer will be in the last cell of the matrix, i.e., dp[n][n]. For Example: Output: 3 Next TopicBuilding 2048 Game in Python |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India