11
11
def damerau_levenshtein_distance (first_string : str , second_string : str ) -> int :
12
12
"""
13
13
Implements the Damerau-Levenshtein distance algorithm that measures
14
- the edit distance between two string .
14
+ the edit distance between two strings .
15
15
16
16
Parameters:
17
- first_string (string) : The first string
18
- second_string (string) : The second string
17
+ first_string: The first string to compare
18
+ second_string: The second string to compare
19
19
20
20
Returns:
21
- distance (int) : The edit distance between the first and second strings
21
+ distance: The edit distance between the first and second strings
22
22
23
23
>>> damerau_levenshtein_distance("cat", "cut")
24
24
1
@@ -32,18 +32,23 @@ def damerau_levenshtein_distance(first_string: str, second_string: str) -> int:
32
32
3
33
33
"""
34
34
35
+ length_of_first_string = len (first_string )
36
+ length_of_second_string = len (second_string )
37
+
35
38
# Create a dynamic programming matrix to store the distances
36
- dp_matrix = [[0 ] * (len (second_string ) + 1 ) for _ in range (len (first_string ) + 1 )]
39
+ dp_matrix = [
40
+ [0 ] * (length_of_second_string + 1 ) for _ in range (length_of_first_string + 1 )
41
+ ]
37
42
38
43
# Initialize the matrix
39
- for i in range (len ( first_string ) + 1 ):
44
+ for i in range (length_of_first_string + 1 ):
40
45
dp_matrix [i ][0 ] = i
41
- for j in range (len ( second_string ) + 1 ):
46
+ for j in range (length_of_second_string + 1 ):
42
47
dp_matrix [0 ][j ] = j
43
48
44
49
# Fill the matrix
45
- for i in range (1 , len ( first_string ) + 1 ):
46
- for j in range (1 , len ( second_string ) + 1 ):
50
+ for i in range (1 , length_of_first_string + 1 ):
51
+ for j in range (1 , length_of_second_string + 1 ):
47
52
cost = 0 if first_string [i - 1 ] == second_string [j - 1 ] else 1
48
53
49
54
dp_matrix [i ][j ] = min (
@@ -62,7 +67,7 @@ def damerau_levenshtein_distance(first_string: str, second_string: str) -> int:
62
67
dp_matrix [i ][j ], dp_matrix [i - 2 ][j - 2 ] + cost
63
68
) # Transposition
64
69
65
- return dp_matrix [len ( first_string )][ len ( second_string ) ]
70
+ return dp_matrix [length_of_first_string ][ length_of_second_string ]
66
71
67
72
68
73
if __name__ == "__main__" :
0 commit comments