Skip to content

Instantly share code, notes, and snippets.

@abdelq
Last active July 2, 2021 05:36
Show Gist options
  • Save abdelq/d183e1106aaded21ecc19bf99d5e4f65 to your computer and use it in GitHub Desktop.
Save abdelq/d183e1106aaded21ecc19bf99d5e4f65 to your computer and use it in GitHub Desktop.
def levenshtein_distance(s1: str, s2: str) -> int:
if s1 == s2:
return 0
if not s1:
return len(s2)
if not s2:
return len(s1)
prev, curr = None, range(len(s2) + 1)
for i in range(len(s1)):
prev, curr = curr, [i + 1] + [0] * len(s2)
for j in range(len(s2)):
curr[j + 1] = min(
prev[j + 1] + 1, # Deletion
curr[j] + 1, # Insertion
prev[j] + (s1[i] != s2[j]), # Substitution
)
return curr[-1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment