Skip to content

Instantly share code, notes, and snippets.

@harshildarji
Last active November 24, 2018 23:19
Show Gist options
  • Save harshildarji/1f1cc4488eac55469e976c73afb25341 to your computer and use it in GitHub Desktop.
Save harshildarji/1f1cc4488eac55469e976c73afb25341 to your computer and use it in GitHub Desktop.
Generating Levenshtein Distance Matrix and finding Minimum Edit Distance
import numpy
s1 = input('input: ').strip().lower(); l1 = len(s1) + 1
s2 = input('target: ').strip().lower(); l2 = len(s2) + 1
m = numpy.empty([l1, l2], dtype = int)
for i in range(l1):
m[i][0] = i
for j in range(l2):
m[0][j] = j
for i in range(1, l1):
for j in range(1, l2):
if s1[i-1] == s2[j-1]:
m[i][j] = min(m[i-1, j] + 1, m[i, j-1] + 1, m[i-1, j-1])
else:
m[i][j] = min(m[i-1, j] + 1, m[i, j-1] + 1, m[i-1, j-1] + 1)
print('\nLevenshtein distance matrix:', m[1:, 1:], sep = '\n')
print('\nMinimum edit distance: ', m[-1][-1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment