Skip to content

Commit 8e8fb0d

Browse files
Merge pull request #921 from Danushka2/master
Levenshtein distance between two words
2 parents caece43 + bf43e80 commit 8e8fb0d

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

levenshtein_distance.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
2+
def levenshtein_dis(wordA, wordB):
3+
4+
wordA = wordA.lower() #making the wordA lower case
5+
wordB = wordB.lower() #making the wordB lower case
6+
7+
8+
#get the length of the words and defining the variables
9+
length_A = len(wordA)
10+
length_B = len(wordB)
11+
max_len = 0
12+
diff = 0
13+
distances = []
14+
distance = 0
15+
16+
17+
#check the difference of the word to decide how many letter should be delete or add
18+
#also store that value in the 'diff' variable and get the max length of the user given words
19+
if length_A > length_B:
20+
diff = length_A - length_B
21+
max_len = length_A
22+
elif length_A < length_B:
23+
diff = length_B - length_A
24+
max_len = length_B
25+
else:
26+
diff = 0
27+
max_len = length_A
28+
29+
30+
#starting from the front of the words and compare the letters of the both user given words
31+
for x in range(max_len-diff):
32+
if wordA[x] != wordB[x]:
33+
distance += 1
34+
35+
#add the 'distance' value to the 'distances' array
36+
distances.append(distance)
37+
distance = 0
38+
39+
#starting from the back of the words and compare the letters of the both user given words
40+
for x in range(max_len-diff):
41+
if wordA[-(x+1)] != wordB[-(x+1)]:
42+
distance += 1
43+
44+
#add the 'distance' value to the 'distances' array
45+
distances.append(distance)
46+
47+
#get the minimun value of the 'distances' array and add it with the 'diff' values and
48+
#store them in the 'diff' variable
49+
diff = diff + min(distances)
50+
51+
#return the value
52+
return diff

0 commit comments

Comments
 (0)