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

Function levenshtein_distance

strings/levenshtein_distance.py:4–51  ·  view source on GitHub ↗

Implementation of the Levenshtein distance in Python. :param first_word: the first word to measure the difference. :param second_word: the second word to measure the difference. :return: the levenshtein distance between the two words. Examples: >>> levenshtein_distance("plan

(first_word: str, second_word: str)

Source from the content-addressed store, hash-verified

2
3
4def levenshtein_distance(first_word: str, second_word: str) -> int:
5 """
6 Implementation of the Levenshtein distance in Python.
7 :param first_word: the first word to measure the difference.
8 :param second_word: the second word to measure the difference.
9 :return: the levenshtein distance between the two words.
10 Examples:
11 >>> levenshtein_distance("planet", "planetary")
12 3
13 >>> levenshtein_distance("", "test")
14 4
15 >>> levenshtein_distance("book", "back")
16 2
17 >>> levenshtein_distance("book", "book")
18 0
19 >>> levenshtein_distance("test", "")
20 4
21 >>> levenshtein_distance("", "")
22 0
23 >>> levenshtein_distance("orchestration", "container")
24 10
25 """
26 # The longer word should come first
27 if len(first_word) < len(second_word):
28 return levenshtein_distance(second_word, first_word)
29
30 if len(second_word) == 0:
31 return len(first_word)
32
33 previous_row = list(range(len(second_word) + 1))
34
35 for i, c1 in enumerate(first_word):
36 current_row = [i + 1]
37
38 for j, c2 in enumerate(second_word):
39 # Calculate insertions, deletions, and substitutions
40 insertions = previous_row[j + 1] + 1
41 deletions = current_row[j] + 1
42 substitutions = previous_row[j] + (c1 != c2)
43
44 # Get the minimum to append to the current row
45 current_row.append(min(insertions, deletions, substitutions))
46
47 # Store the previous row
48 previous_row = current_row
49
50 # Returns the last element (distance)
51 return previous_row[-1]
52
53
54def levenshtein_distance_optimized(first_word: str, second_word: str) -> int:

Callers 1

Calls 1

appendMethod · 0.45

Tested by

no test coverage detected