Skip to content

Commit 795681f

Browse files
committed
Add edit distance algorithm in python
1 parent df4f3e5 commit 795681f

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Helpful tutorial: https://www.youtube.com/watch?v=We3YDTzNXEk
2+
# Useful link: https://en.wikipedia.org/wiki/Edit_distance
3+
def get_edit_distance(s1, s2):
4+
5+
l1 = len(s1) + 1
6+
l2 = len(s2) + 1
7+
edit_table = {}
8+
for i in range(l1):
9+
edit_table[i, 0] = i
10+
11+
for j in range(l2):
12+
edit_table[0, j] = j
13+
14+
for i in range(1, l1):
15+
for j in range(1, l2):
16+
edit_table[i, j] = min(edit_table[i - 1, j], edit_table[i, j - 1],
17+
edit_table[i - 1, j - 1])
18+
if s1[i - 1] != s2[j - 1]:
19+
edit_table[i, j] += 1
20+
21+
return edit_table[i, j]
22+
23+
24+
if __name__ == '__main__':
25+
# returns 1 as adding 'a' in 2nd postion to
26+
# 'hello' will make it 'haello'
27+
print get_edit_distance('hello', 'haello')
28+
# returns 2 as replacing 'o' in 'redor' and adding 'e' at the end will make
29+
# 'redare'
30+
print get_edit_distance('redor', 'redare')
31+

0 commit comments

Comments
 (0)