We need to implement a Python function to calculate Levenshtein distance between strings. The problem likely expects a standard implementation. Levenshtein distance is the minimum number of single-character edits (insertions, deletions, substitutions) required to change one string into another.
We need to provide the function. Possibly include docstring. Might need to handle edge cases.
We can implement with dynamic programming using a matrix of size (len(a)+1) x (len(b)+1). Initialize first row and column with 0..len, then fill.
But we can also implement with two rows to save memory.
Let's decide: The problem says "Implement a Python function". It might be part of a coding test. Should be correct and efficient.
We'll implement:
def levenshtein_distance(s1, s2):
if len(s1) < len(s2):
s1, s2 = s2, s1 # ensure s2 is shorter? Not necessary, but two-row method often uses that for memory.
# Actually typical optimization: use only two rows.
We'll do two-row method:
Let m = len(s1), n = len(s2)
Create two arrays of length n+1: previous and current.
Initialize previous = [i for i in range(n+1)]
For i from 1 to m:
current[0] = i
For j from 1 to n:
cost = 0 if s1[i-1] == s2[j-1] else 1
current[j] = min(previous[j] + 1, # deletion from s1? Actually careful: Typically:
current[j-1] + 1, # insertion
previous[j-1] + cost) # substitution
After each i, set previous = current, and perhaps reassign new list for next iteration.
We'll need to swap or copy. Better to use list assignment and create new list each row.
Implementation:
def levenshtein_distance(s1, s2):
m, n = len(s1), len(s2)
if m < n:
# optional: swap to use less memory? Actually two rows uses O(min(m,n)) if we set the shorter as column size.
# But we can also just compute without swapping, but we can swap to minimize memory if we want.
return levenshtein_distance(s2, s1)
code
# Now m >= n
previous = list(range(n + 1))
for i in range(1, m + 1):
current = [0] * (n + 1)
current[0] = i
for j in range(1, n + 1):
cost = 0 if s1[i - 1] == s2[j - 1] else 1
current[j] = min(previous[j] + 1, # deletion (remove char from s1)
current[j - 1] + 1, # insertion (add char to s1)
previous[j - 1] + cost) # substitution or match
previous = current
return previous[n]
But we need to ensure correct indexing. Yes.
We could also implement without swapping, but using two rows always with length of second string.
Edge cases: empty strings. Works.
Time complexity O(m*n), space O(min(m,n)).
Add docstring: "Compute Levenshtein distance between two strings."
Let's test mentally:
s1="kitten", s2="sitting". Should be 3.
m=6, n=7? Actually "kitten" length 6, "sitting" length 7. If we swap, then we will have s1 = "sitting" (7), s2 = "kitten" (6). That works.
Compute manually? Not needed.
We'll produce the function.
But note: The problem might expect a straightforward DP matrix implementation. But two-row is fine.
We'll produce final answer with code and maybe a brief explanation.
We need to output only the code? Usually the instruction: "Implement a Python function to calculate the Levenshtein distance between strings." So we need to write the function. Possibly include some example usage? Probably just the function definition.
Now let's think about potential pitfalls: We must ensure that if we swap, we are using the swapped strings for cost comparison. In the above approach, we swap if m < n to have s1 as longer. But then we use s1[i-1] and s2[j-1] in cost. After swapping, the original order might not matter because distance is symmetric. However, we need to ensure we are computing the correct distance. The algorithm is symmetric. So swapping is fine.
But careful: When we swap, we call the function recursively. That's okay but recursion depth not issue. However we could do it iteratively without recursion: simply assign s1, s2 = (s2, s1) if len(s1) < len(s2) else (s1, s2). That avoids recursion. I'll do that:
def levenshtein_distance(s1, s2):
# Ensure s2 is the shorter string for memory efficiency
if len(s1) < len(s2):
s1, s2 = s2, s1
m, n = len(s1), len(s2)
previous = list(range(n+1))
for i in range(1, m+1):
current = [i] + [0]n # Actually we can set current[0] = i; easier: current = [0](n+1); current[0]=i
# We'll do: current = [0]*(n+1); current[0] = i
current = [0] * (n+1)
current[0] = i
for j in range(1, n+1):
cost = 0 if s1[i-1] == s2[j-1] else 1
current[j] = min(previous[j] + 1,
current[j-1] + 1,
previous[j-1] + cost)
previous = current
return previous[n]
Yes.
Now check: If s1 and s2 are swapped, we still compute correct distance.
Test: s1="", s2="abc". Then after swap? len(s1)=0 < len(s2)=3, so swap: s1="abc", s2="". m=3, n=0. previous = [0] (since range(0+1)=[0]). Loop i from 1 to 3: current = [i] + ... but n=0 so current length 1. current[0]=i. Then for j from 1 to n: loop does nothing. previous=current. At end, previous[0] = 3. Return 3, which is correct (insert 3 chars).
If both empty: m=0, n=0. previous=[0]. No loops. Return previous[0]=0.
Works.
Now, maybe they want a simple matrix implementation for clarity. But two-row is fine.
We can also implement using list comprehension.
I'll output the function with docstring and maybe a test example but not required.
Let's write final answer.
python
def levenshtein_distance(s1: str, s2: str) -> int:
"""
Compute the Levenshtein distance (edit distance) between two strings.
The Levenshtein distance is the minimum number of single-character edits
(insertions, deletions, or substitutions) required to change one string
into the other.
Args:
s1 (str): First string.
s2 (str): Second string.
Returns:
int: The edit distance.
"""
# Make s1 the longer string to minimize memory (distance is symmetric)
if len(s1) < len(s2):
s1, s2 = s2, s1
m, n = len(s1), len(s2)
# previous row of distances, initially for an empty prefix of s1
previous = list(range(n + 1))
for i in range(1, m + 1):
# current row; distance for empty prefix of s2 is i
current = [0] * (n + 1)
current[0] = i
for j in range(1, n + 1):
# cost is 0 if characters match, else 1
cost = 0 if s1[i - 1] == s2[j - 1] else 1
# compute minimum of deletion, insertion, and substitution
current[j] = min(
previous[j] + 1, # deletion
current[j - 1] + 1, # insertion
previous[j - 1] + cost # substitution or match
)
previous = current
return previous[n]