Skip to content

Instantly share code, notes, and snippets.

@hunan-rostomyan
Created November 2, 2016 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hunan-rostomyan/9cc21a685126dd55ea563543b4c042be to your computer and use it in GitHub Desktop.
Save hunan-rostomyan/9cc21a685126dd55ea563543b4c042be to your computer and use it in GitHub Desktop.
Levenshtein distance
def memo(f):
"""Basic memoizer for positional parameters."""
table = {}
def _f(*args):
if (args) not in table:
table[(args)] = f(*args)
return table[(args)]
return _f
def edit_distance(s, t):
"""Compute the Levenshtein distance between two sequences."""
def diff(i, j):
return 1 if s[i - 1] != t[j - 1] else 0
@memo
def aux(i, j):
if i == 0:
return j
if j == 0:
return i
insert = aux(i - 1, j) + 1
delete = aux(i, j - 1) + 1
replace = aux(i - 1, j - 1) + diff(i, j)
return min(insert, delete, replace)
return aux(len(s), len(t))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment