MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / levenshtein_distance_optimized

Function levenshtein_distance_optimized

strings/levenshtein_distance.py:54–96  ·  view source on GitHub ↗

Compute the Levenshtein distance between two words (strings). The function is optimized for efficiency by modifying rows in place. :param first_word: the first word to measure the difference. :param second_word: the second word to measure the difference. :return: the Levenshtein

(first_word: str, second_word: str)

Source from the content-addressed store, hash-verified

52
53
54def levenshtein_distance_optimized(first_word: str, second_word: str) -> int:
55 """
56 Compute the Levenshtein distance between two words (strings).
57 The function is optimized for efficiency by modifying rows in place.
58 :param first_word: the first word to measure the difference.
59 :param second_word: the second word to measure the difference.
60 :return: the Levenshtein distance between the two words.
61 Examples:
62 >>> levenshtein_distance_optimized("planet", "planetary")
63 3
64 >>> levenshtein_distance_optimized("", "test")
65 4
66 >>> levenshtein_distance_optimized("book", "back")
67 2
68 >>> levenshtein_distance_optimized("book", "book")
69 0
70 >>> levenshtein_distance_optimized("test", "")
71 4
72 >>> levenshtein_distance_optimized("", "")
73 0
74 >>> levenshtein_distance_optimized("orchestration", "container")
75 10
76 """
77 if len(first_word) < len(second_word):
78 return levenshtein_distance_optimized(second_word, first_word)
79
80 if len(second_word) == 0:
81 return len(first_word)
82
83 previous_row = list(range(len(second_word) + 1))
84
85 for i, c1 in enumerate(first_word):
86 current_row = [i + 1] + [0] * len(second_word)
87
88 for j, c2 in enumerate(second_word):
89 insertions = previous_row[j + 1] + 1
90 deletions = current_row[j] + 1
91 substitutions = previous_row[j] + (c1 != c2)
92 current_row[j + 1] = min(insertions, deletions, substitutions)
93
94 previous_row = current_row
95
96 return previous_row[-1]
97
98
99def benchmark_levenshtein_distance(func: Callable) -> None:

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected