Edit distance algorithm is a string metric, i.e., it is a way of quantifying how dissimilar two strings are to one another. It is measured by counting the minimum number of operations required to transform one string into another. This implementation assumes that the cost of operat
(source: str, target: str)
| 1 | def edit_distance(source: str, target: str) -> int: |
| 2 | """ |
| 3 | Edit distance algorithm is a string metric, i.e., it is a way of quantifying how |
| 4 | dissimilar two strings are to one another. It is measured by counting the minimum |
| 5 | number of operations required to transform one string into another. |
| 6 | |
| 7 | This implementation assumes that the cost of operations (insertion, deletion and |
| 8 | substitution) is always 1 |
| 9 | |
| 10 | Args: |
| 11 | source: the initial string with respect to which we are calculating the edit |
| 12 | distance for the target |
| 13 | target: the target string, formed after performing n operations on the source string |
| 14 | |
| 15 | >>> edit_distance("GATTIC", "GALTIC") |
| 16 | 1 |
| 17 | >>> edit_distance("NUM3", "HUM2") |
| 18 | 2 |
| 19 | >>> edit_distance("cap", "CAP") |
| 20 | 3 |
| 21 | >>> edit_distance("Cat", "") |
| 22 | 3 |
| 23 | >>> edit_distance("cat", "cat") |
| 24 | 0 |
| 25 | >>> edit_distance("", "123456789") |
| 26 | 9 |
| 27 | >>> edit_distance("Be@uty", "Beautyyyy!") |
| 28 | 5 |
| 29 | >>> edit_distance("lstring", "lsstring") |
| 30 | 1 |
| 31 | """ |
| 32 | if len(source) == 0: |
| 33 | return len(target) |
| 34 | elif len(target) == 0: |
| 35 | return len(source) |
| 36 | |
| 37 | delta = int(source[-1] != target[-1]) # Substitution |
| 38 | return min( |
| 39 | edit_distance(source[:-1], target[:-1]) + delta, |
| 40 | edit_distance(source, target[:-1]) + 1, |
| 41 | edit_distance(source[:-1], target) + 1, |
| 42 | ) |
| 43 | |
| 44 | |
| 45 | if __name__ == "__main__": |