Skip to content

Commit eb49608

Browse files
committedOct 3, 2022
Added Levenshtein distance.py
1 parent bc006ea commit eb49608

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
 

‎Levenshtein_distance.py

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# The Levenshtein distance (Edit distance) Problem
2+
3+
# Informally, the Levenshtein distance between two words is
4+
# the minimum number of single-character edits (insertions, deletions or substitutions)
5+
# required to change one word into the other.
6+
7+
# For example, the Levenshtein distance between kitten and sitting is 3.
8+
# The minimal edit script that transforms the former into the latter is:
9+
10+
# kitten —> sitten (substitution of s for k)
11+
# sitten —> sittin (substitution of i for e)
12+
# sittin —> sitting (insertion of g at the end)
13+
14+
def levenshtein_distance(word_1, chars_1, word_2, chars_2):
15+
# base case if the strings are empty
16+
if chars_1 == 0:
17+
return chars_2
18+
if chars_2 == 0:
19+
return chars_1
20+
21+
# if last characters of the string match, the cost of
22+
# operations is 0, i.e. no changes are made
23+
if word_1[chars_1 - 1] == word_2[chars_2 - 1]:
24+
cost = 0
25+
else:
26+
cost = 1
27+
28+
# calculating the numbers of operations recursively
29+
deletion = levenshtein_distance(word_1, chars_1 - 1, word_2, chars_2) + 1
30+
insertion = levenshtein_distance(word_1, chars_1, word_2, chars_2 - 1) + 1
31+
substitution = levenshtein_distance(word_1, chars_1 - 1, word_2, chars_2 - 1) + cost
32+
33+
return min(deletion, insertion, substitution)
34+
35+
# driving script
36+
if __name__ == '__main__':
37+
word_1 = input("Enter Word 1 :")
38+
word_2 = input("Enter Word 2 :")
39+
40+
print('The Levenshtein distance is:')
41+
print(levenshtein_distance(word_1, len(word_1), word_2, len(word_2)))

0 commit comments

Comments
 (0)
Please sign in to comment.