Last active
May 12, 2016 07:42
-
-
Save mattgathu/5bd17a0e2c1651584fd4c866baacea23 to your computer and use it in GitHub Desktop.
Levenshtein distance between a and b
This file contains 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 levenshtein(a,b): | |
"Calculates the Levenshtein distance between a and b." | |
n, m = len(a), len(b) | |
if n > m: | |
# Make sure n <= m, to use O(min(n,m)) space | |
a,b = b,a | |
n,m = m,n | |
current = range(n+1) | |
for i in range(1,m+1): | |
previous, current = current, [i]+[0]*n | |
for j in range(1,n+1): | |
add, delete = previous[j]+1, current[j-1]+1 | |
change = previous[j-1] | |
if a[j-1] != b[i-1]: | |
change = change + 1 | |
current[j] = min(add, delete, change) | |
return current[n] | |
if __name__=="__main__": | |
from sys import argv | |
print(levenshtein(argv[1],argv[2])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment