Anagram checking in Python program using collections.Counter()


Two strings are said to be anagrams of each if they have same characters even in different order. In this tutorial, we are going to check for anagram in Python using the collections.Counter() method.

Input:
string_one = "cat"
string_two = "tac"
Ouput:
True

collections.Counter()

collection.Counter() returns a dictionary which contains frerquency of each character from the string. Counter object have different methods to find most common elements, unique elements, count, etc..,

Let's see one example.

Example

# importing the collections module
import collections
# creating Counter object
counter = collections.Counter("Hafeez")
# printing the counter
print(counter)
# displaying most common character from the string
print("\nMost common character")
print(counter.most_common(1))

Output

If you run the above program, you will get the following results.

Counter({'e': 2, 'H': 1, 'a': 1, 'f': 1, 'z': 1})
Most common character
[('e', 2)]

Steps to check for the anagram.

Algorithm

1. Initialise two strings.
2. Create collections.Counter() objects for both strings.
3. If both of the objects are equal.
   3.1. Print True
4. Else print False

Let's see one example.

Example

# importing the collections module
import collections
# initializing strings
string_one = "cat"
string_two = "atc"
# checking the Counter objects of both strings
if collections.Counter(string_one) == collections.Counter(string_two):
   # they are equal so, printing True
   print(True)
else:
   # they are not equal so, printing False
   print(False)

Output

If you run the above program, you will get the following results.

True

Conclusion

If you are facing any problem in following the tutorial, mention them in the comment section.

raja
Published on 04-Nov-2019 07:22:52
Advertisements