Grok 4.1 Fast· xai
Frontier Reasoning Traces
Implement a Python function to calculate the Levenshtein distance between strings.
- User
Implement a Python function to calculate the Levenshtein distance between strings.
- Assistant
def levenshtein_distance(s1: str, s2: str) -> int: """ Calculate the Levenshtein distance between two strings. The Levenshtein distance is the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one word into the other. Args: s1 (str): First string. s2 (str): Second string. Returns: int: The Levenshtein distance. Examples: >>> levenshtein_distance("kitten", "sitting") 3 >>> levenshtein_distance("Sunday", "Saturday") 3 >>> levenshtein_distance("", "a") 1 """ m, n = len(s1), len(s2) dp = [[0] * (n + 1) for _ in range(m + 1)] # Base cases: deletions for i in range(m + 1): dp[i][0] = i # Base cases: insertions for j in range(n + 1): dp[0][j] = j for i in range(1, m + 1): for j in range(1, n + 1): if s1[i - 1] == s2[j - 1]: dp[i][j] = dp[i - 1][j - 1] else: dp[i][j] = 1 + min( dp[i - 1][j], # deletion dp[i][j - 1], # insertion dp[i - 1][j - 1] # substitution ) return dp[m][n]
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.