I have written a function which calculates the Levenshtein distance between two given strings. However, it seems that it is not working correctly. substitution cost = 2, insertion cost = 1, deletion cost = 1
def MyLevenshtein(String1, String2): if len(String1) and len(String2) != 0: rows = len(String1) + 1 columns = len(String2) + 1 distance = [[0 for x in range(columns)] for x in range(rows)] for i in range(1, rows): distance[i] = i for i in range(1, columns): distance[i] = i for column in range(1, columns): for row in range(1, rows): if String1[row - 1] == String2[column - 1]: cost = 0 else: cost = 2 distance[row][column] = min(distance[row - 1][column] + 1, # deletion distance[row][column - 1] + 1, # insertion distance[row - 1][column - 1] + cost) #substitution Distance = distance[row][column] return Distance
For example, when I call the function with the strings 'hamchenoonan" and 'hamchenin', 5 is returned, although it should return 7.