Skip to content

Instantly share code, notes, and snippets.

@curzona
curzona / levenshtein.py
Created March 8, 2014 17:49
Python implementation of the Levenshtein distance with edits
# Calculates the levenshtein distance and the edits between two strings
def levenshtein(s1, s2, key=hash):
rows = costmatrix(s1, s2, key)
edits = backtrace(s1, s2, rows, key)
return rows[-1][-1], edits
# Generate the cost matrix for the two strings
# Based on http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python
def costmatrix(s1, s2, key=hash):