I'll help you write code for calculating edit distance (Levenshtein distance). Here's an implementation using dynamic programming:
def edit_distance(str1, str2):
"""
Calculate the minimum edit distance between two strings.
Args:
str1: First string
str2: Second string
Returns:
The minimum number of operations (insert, delete, substitute)
needed to transform str1 into str2
"""
m, n = len(str1), len(str2)
# Create a DP table with dimensions (m+1) x (n+1)
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Base cases: converting empty string to str2 or str1 to empty string
for i in range(m + 1):
dp[i][0] = i # Delete all characters from str1
for j in range(n + 1):
dp[0][j] = j # Insert all characters from str2
# Fill the DP table
for i in range(1, m + 1):
for j in range(1, n + 1):
if str1[i-1] == str2[j-1]:
# Characters match, no operation needed
dp[i][j] = dp[i-1][j-1]
else:
# Take minimum of three operations
dp[i][j] = 1 + min(
dp[i-1][j], # Delete from str1
dp[i][j-1], # Insert into str1
dp[i-1][j-1] # Substitute in str1
)
return dp[m][n]
def edit_distance_with_operations(str1, str2):
"""
Calculate edit distance and return the sequence of operations.
Returns:
(distance, operations) where operations is a list of
(operation_type, position, character) tuples
"""
m, n = len(str1), len(str2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Initialize base cases
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
# Fill DP table
for i in range(1, m + 1):
for j in range(1, n + 1):
if str1[i-1] == str2[j-1]:
dp[i][j] = dp[i-1][j-1]
else:
dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
# Backtrack to find operations
operations = []
i, j = m, n
while i > 0 or j > 0:
if i == 0:
operations.append(("INSERT", i, str2[j-1]))
j -= 1
elif j == 0:
operations.append(("DELETE", i-1, str1[i-1]))
i -= 1
elif str1[i-1] == str2[j-1]:
i -= 1
j -= 1
else:
min_val = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
if dp[i-1][j-1] == min_val:
operations.append(("SUBSTITUTE", i-1, f"{str1[i-1]}→{str2[j-1]}"))
i -= 1
j -= 1
elif dp[i-1][j] == min_val:
operations.append(("DELETE", i-1, str1[i-1]))
i -= 1
else:
operations.append(("INSERT", i, str2[j-1]))
j -= 1
operations.reverse()
return dp[m][n], operations
# Example usage
if __name__ == "__main__":
# Basic examples
print(edit_distance("kitten", "sitting")) # Output: 3
print(edit_distance("saturday", "sunday")) # Output: 3
print(edit_distance("", "abc")) # Output: 3
print(edit_distance("abc", "abc")) # Output: 0
# Example with operations
str1, str2 = "kitten", "sitting"
distance, ops = edit_distance_with_operations(str1, str2)
print(f"\nTransforming '{str1}' to '{str2}':")
print(f"Edit distance: {distance}")
print("Operations:")
for op in ops:
print(f" {op}")
This implementation includes:
- Basic edit distance function: Calculates the minimum number of operations needed
- Extended version: Also tracks the actual operations performed
- Time complexity: O(m×n) where m and n are the lengths of the strings
- Space complexity: O(m×n) for the DP table
The algorithm works by building a table where dp[i][j] represents the edit distance between the first i characters of str1 and the first j characters of str2.
Would you like me to explain the algorithm in more detail, show an optimization for space complexity, or implement it in a different programming language?