Created
September 22, 2014 23:12
-
-
Save pedramamini/0ac03c3fad3b0804f69c to your computer and use it in GitHub Desktop.
Provides the Levenshtein distance between two strings. ie: The number of transformations required to transform one string to the other
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 levenshtein_distance (first, second): | |
""" | |
Provides the Levenshtein distance between two strings. ie: The number of transformations required to transform | |
one string to the other. | |
@type first: String | |
@param first: First string. | |
@type second: String | |
@param second: Second string. | |
@rtype: Integer | |
@return: Distance between strings. | |
""" | |
if len(first) > len(second): | |
first, second = second, first | |
if len(second) == 0: | |
return len(first) | |
first_length = len(first) + 1 | |
second_length = len(second) + 1 | |
distance_matrix = [range(second_length) for x in range(first_length)] | |
for i in range(1, first_length): | |
for j in range(1, second_length): | |
deletion = distance_matrix[i-1][j] + 1 | |
insertion = distance_matrix[i][j-1] + 1 | |
substitution = distance_matrix[i-1][j-1] | |
if first[i-1] != second[j-1]: | |
substitution += 1 | |
distance_matrix[i][j] = min(insertion, deletion, substitution) | |
return distance_matrix[first_length-1][second_length-1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
a little diff