803
In this example we use python to check if two strings are anagrams or not.
Example 1
In this example we use the sorted method which sorts the two strings in alphabetical order, and the if condition checks whether both the sorted strings are equal or not.
If this evaluates to True, the two strings are anagram.
myString1 = input("Enter the First String = ") myString2 = input("Enter the Second String = ") if(sorted(myString1) == sorted(myString2)): print("The Two Strings are Anagrams.") else: print("The Two Strings are not Anagrams.")
You will see the following
>>> %Run isanagram1.py Enter the First String = tired Enter the Second String = tried The Two Strings are Anagrams. >>> %Run isanagram1.py Enter the First String = tore Enter the Second String = tire The Two Strings are not Anagrams.
Example 2
We will use a collection in this example
from collections import Counter myString1 = input("Enter the First String = ") myString2 = input("Enter the Second String = ") if(Counter(myString1) == Counter(myString2)): print("The Two Strings are Anagrams.") else: print("The Two Strings are not Anagrams.")
You will see the following
>>> %Run isanagram2.py Enter the First String = tired Enter the Second String = tried The Two Strings are Anagrams. >>> %Run isanagram2.py Enter the First String = tore Enter the Second String = tire The Two Strings are not Anagrams.
Link
This is in our github repository
https://github.com/programmershelp/maxpython/tree/main/code%20example/String%20examples