Edit Distance Levenshtein DP (Python)

Compute the Levenshtein edit distance between two strings with insert, delete, and substitute operations.

PythonData Integrity

Code

pythonsnippet
12 lines
def edit_distance(a, b):
    m, n = len(a), len(b)
    prev = list(range(n + 1))
    for i in range(1, m + 1):
        curr = [i] + [0] * n
        for j in range(1, n + 1):
            if a[i - 1] == b[j - 1]:
                curr[j] = prev[j - 1]
            else:
                curr[j] = 1 + min(prev[j], curr[j - 1], prev[j - 1])
        prev = curr
    return prev[n]

How it works

Edit Distance Levenshtein DP (Python) comes down to the function edit_distance.

Repetition is confined to for i in range(1, m + 1) — the rest of the file is straight-line.

Using it

The primary signature is def edit_distance(a, b)

Import edit_distance from the file and call it — the rest of the code is implementation detail.

Interactive Tools for This Topic

FAQ

Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `edit_distance` at load time.