The following code is a Python-based implementation of the iterative Levenshtein distance:
def iterative_levenshtein(a, b):
rows = len(a)+1 cols = len(b)+1
dist = [[0 for x in range(cols)]
for x in range(rows)]
The preceding dist[i,j] function contains the Levenshtein distance between the i and j characters of the sequences a and b:
#edit distance by deleting character
for i in range(1, rows):
dist[i][0] = i
# edit distance by inserting the characters
for i in range(1, cols): dist[0][i] = i
The edit distances are computed either by deleting or by inserting characters from/into the string sequences:
for col in range(1, cols):
for row in range(1, rows):
if s[row-1] == t[col-1]:
cost = 0
else:
cost = 1
dist[row][col] = min(dist[row-1][col] + 1,
# by deletes
dist[row][col-1] + 1, # by inserts
dist[row-1][col-1] + cost) # by substitutes
Finally, we print the distance between abclegit.com and abcleg1t.com, as shown in the following code:
for r in range(rows):
print(dist[r])
return
dist[row][col]print(iterative_levenshtein("abclegit", "abcleg1t"))