Levenshtein distance between two strings is defined as the minimum number of characters needed to insert, delete or replace in a given string string1 to transform it to another string string2.
Examples :
Input : string1 = “geek”, string2 = “gesek”
Output : 1
Explanation : We can convert string1 into str2 by inserting a ‘s’.Input : str1 = “cat”, string2 = “cut”
Output : 1
Explanation : We can convert string1 into str2 by replacing ‘a’ with ‘u’.Input : string1 = “sunday”, string2 = “saturday”
Output : 3
Explanation : Last three and first characters are same. We basically need to convert “un” to “atur”. This can be done using below three operations. Replace ‘n’ with ‘r’, insert t, insert a
The Levenshtein distance between two strings can be found using the enchant.utils.levenshtein()
method of the enchant
module.
enchant.utils.levenshtein()
Syntax : enchant.utils.levenshtein(string1, string2)
Parameters :
string1 : the first string to be compared
string2 : the second string to be comparedReturns : an integer denoting the Levenshtein distance
# import the enchant module import enchant # determining the values of the parameters string1 = "abc" string2 = "aef" # the Levenshtein distance between # string1 and string2 print (enchant.utils.levenshtein(string1, string2)) |
Output :
2
Example 2:
# import the enchant module import enchant # determining the values of the parameters string1 = "Hello World" string2 = "Hello d" # the Levenshtein distance between # string1 and string2 print (enchant.utils.levenshtein(string1, string2)) |
Output :
4
Example 3:
# import the enchant module import enchant # determining the values of the parameters string1 = "Computer Science Portal" string2 = "Computer Portal" # the Levenshtein distance between # string1 and string2 print (enchant.utils.levenshtein(string1, string2)) |
Output :
8
<!–
–>
Please Login to comment…