Edit Distance Levenshtein DP (Python)
Compute the Levenshtein edit distance between two strings with insert, delete, and substitute operations.
Code
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
Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.