How to calculate Levenshtein distance in Python?

By Shivang Yadav Last updated : November 21, 2023

Levenshtein Distance

Levenshtein distance (edit distance) is a metric used to measure the similarity or dissimilarity between two strings.

It quantifies the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one string into the other.

Here, The formula to calculate the Levenshtein distance between two strings, "s1" and "s2," as follows:

D(s1, s2) = D(len(s1), len(s2))

Where:

  • D(i, j) is the Levenshtein distance between the first i characters of s1 and the first j characters of s2.
  • len(s1) is the length of string s1.
  • len(s2) is the length of string s2.

Calculation of Levenshtein Distance

The Levenshtein Distance for two strings is calculated in Python using the lev() method present in the Levenshtein Library of Python.

The lev() method

The lev() method in Python takes two strings and calculates the Levenshtein distance.

Syntax:

lev(string1, string2)

Python program to calculate Levenshtein distance for string

from Levenshtein import distance as lev

# Declaring Strings
string1 = "include"
string2 = "includes"

print("String 1 {string1} \nString 2 {string2}")

lDist = lev(string1, string2)
print(f"The Levenshtein Distance between the strings is {lDist}")

Output

The output of the above program is:

String 1 {string1} 
String 2 {string2}
The Levenshtein Distance between the strings is 1

Python SciPy Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.