Created
November 2, 2016 22:38
-
-
Save hunan-rostomyan/9cc21a685126dd55ea563543b4c042be to your computer and use it in GitHub Desktop.
Levenshtein distance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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