Anagram checking in Python using collections.Counter()



When two strings have same characters but arranged in different orders then they are called anagrams. For example, spot and post are anagrams as they have same letters forming different words. In this article we will see how can we check if two strings are anagrams of each other or not.

For this we use the python module called collections. This are used to store collections of data, like list, dict, set, tuple etc. These are example of built-in collections. The function counter() simply counts the number of times an element is present in a collection and returns the result as a dictionary showing the element and its count. So, if two strings have matching count of each of the character present in them then we consider them as anagrams.

Example

 Live Demo

from collections import Counter
StringA = 'top spot'
StringB = 'pot post'
# Print the elements as adictionary
print Counter(StringA)
print Counter(StringB)
# Compare the dictionaries
if Counter(StringA)== Counter(StringB):
print 'StringA and StringB are Anagrams'

Output

Running the above code gives us the following result −

Counter({'p': 2, 't': 2, 'o': 2, 's': 1, ' ': 1})
Counter({'p': 2, 't': 2, 'o': 2, 's': 1, ' ': 1})
StringA and StringB are Anagrams

Advertisements