def edit_distance(a, b):
prev = list(range(len(b) + 1))
for i in range(1, len(a) + 1):
cur = [i] + [0] * len(b)
for j in range(1, len(b) + 1):
cost = 0 if a[i - 1] == b[j - 1] else 1
cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost)
prev = cur
return prev[-1]
words = ["receive", "relieve", "recipe", "deceive"]
typed = "recieve"
ranked = sorted(words, key=lambda w: (edit_distance(typed, w), w))
for w in ranked:
print(w, edit_distance(typed, w))
For the activity: a memory-saving version that keeps only two rows of the table, and sorted with a key that sorts by distance, then alphabetically.