Skip to content

Commit dd0cc28

Browse files
committed
refactor: use variable for length and doc correction
1 parent 816119d commit dd0cc28

File tree

1 file changed

+15
-10
lines changed

1 file changed

+15
-10
lines changed

strings/damerau_levenshtein_distance.py

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,14 @@
1111
def damerau_levenshtein_distance(first_string: str, second_string: str) -> int:
1212
"""
1313
Implements the Damerau-Levenshtein distance algorithm that measures
14-
the edit distance between two string.
14+
the edit distance between two strings.
1515
1616
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
1919
2020
Returns:
21-
distance (int): The edit distance between the first and second strings
21+
distance: The edit distance between the first and second strings
2222
2323
>>> damerau_levenshtein_distance("cat", "cut")
2424
1
@@ -32,18 +32,23 @@ def damerau_levenshtein_distance(first_string: str, second_string: str) -> int:
3232
3
3333
"""
3434

35+
length_of_first_string = len(first_string)
36+
length_of_second_string = len(second_string)
37+
3538
# 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+
]
3742

3843
# Initialize the matrix
39-
for i in range(len(first_string) + 1):
44+
for i in range(length_of_first_string + 1):
4045
dp_matrix[i][0] = i
41-
for j in range(len(second_string) + 1):
46+
for j in range(length_of_second_string + 1):
4247
dp_matrix[0][j] = j
4348

4449
# 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):
4752
cost = 0 if first_string[i - 1] == second_string[j - 1] else 1
4853

4954
dp_matrix[i][j] = min(
@@ -62,7 +67,7 @@ def damerau_levenshtein_distance(first_string: str, second_string: str) -> int:
6267
dp_matrix[i][j], dp_matrix[i - 2][j - 2] + cost
6368
) # Transposition
6469

65-
return dp_matrix[len(first_string)][len(second_string)]
70+
return dp_matrix[length_of_first_string][length_of_second_string]
6671

6772

6873
if __name__ == "__main__":

0 commit comments

Comments
 (0)