from difflib import SequenceMatcher def similar(a, b): return SequenceMatcher(None, a, b).ratio() >>> similar("Apple","Appel") 0.8 >>> similar("Apple","Mango") 0.0
Here is what the above code is Doing:
1. We are importing the SequenceMatcher class from the difflib module.
2. We are creating a function named similar that takes two strings as arguments.
3. We are creating a SequenceMatcher object by passing None as the first argument.
4. We are calling the ratio() method on the SequenceMatcher object and storing the return value in a variable named result.
5. We are returning the value stored in the result variable.
6. We are calling the similar function by passing “Apple” and “Appel” as arguments.
7. We are calling the similar function by passing “Apple” and “Mango” as arguments.
The output of the above code will be:
As you can see, the similar function returns 1.0 when the two strings are exactly the same, 0.0 when the two strings have nothing in common, and a value between 0.0 and 1.0 when the two strings have something in common.