Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Anagram checking in Python program using collections.Counter()
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once. For example, thing and night are anagrams of each other.
In this article, we are going to learn how to check an anagram in a Python program using collections.Counter() method. This method counts the number of occurrences of each element in a collection (like characters in a string), helping us to compare two words for identical character counts ?
Understanding the Problem
<b>Input:</b> str1= "listen", str2= "silent" <b>Output:</b> True
Two strings are said to be anagrams when using the collections.Counter(), only if their counter representations are equal ?
from collections import Counter
print(Counter("listen"))
print(Counter("silent"))
Counter({'l': 1, 'i': 1, 's': 1, 't': 1, 'e': 1, 'n': 1})
Counter({'s': 1, 'i': 1, 'l': 1, 'e': 1, 'n': 1, 't': 1})
Here, both strings have identical character counts, hence they are anagrams. Two strings are anagrams if they contain the same characters with the same frequency, even in different order.
The collections.Counter() Method
The Counter is a subclass of the dict class in the collections module. It counts items in iterables and stores them as dictionary keys with their counts as values.
Syntax
from collections import Counter Counter(iterable)
Example 1: Basic Anagram Check
Let's check whether two simple strings are anagrams ?
from collections import Counter
def check_anagram(str1, str2):
return Counter(str1) == Counter(str2)
print(check_anagram("listen", "silent"))
print(check_anagram("hello", "world"))
True False
Example 2: Phrases with Spaces
Consider checking anagrams for phrases that contain spaces. We need to remove spaces and convert to lowercase for accurate comparison ?
from collections import Counter
def check_anagram_phrase(str1, str2):
# Remove spaces and convert to lowercase
cleaned_str1 = str1.replace(" ", "").lower()
cleaned_str2 = str2.replace(" ", "").lower()
return Counter(cleaned_str1) == Counter(cleaned_str2)
print(check_anagram_phrase("School master", "The classroom"))
print(check_anagram_phrase("A gentleman", "Elegant man"))
True True
Example 3: Different Length Strings
When strings have different lengths, they cannot be anagrams ?
from collections import Counter
def check_anagram_phrase(str1, str2):
cleaned_str1 = str1.replace(" ", "").lower()
cleaned_str2 = str2.replace(" ", "").lower()
return Counter(cleaned_str1) == Counter(cleaned_str2)
print(check_anagram_phrase("Hi", "hiiii"))
print(check_anagram_phrase("cat", "act"))
False True
Complete Anagram Checker Function
Here's a comprehensive function that handles various cases ?
from collections import Counter
def is_anagram(str1, str2):
# Handle None or empty strings
if not str1 or not str2:
return False
# Remove spaces, punctuation, and convert to lowercase
clean1 = ''.join(char.lower() for char in str1 if char.isalpha())
clean2 = ''.join(char.lower() for char in str2 if char.isalpha())
# Compare character counts
return Counter(clean1) == Counter(clean2)
# Test cases
test_cases = [
("listen", "silent"),
("The Eyes", "They See"),
("astronomer", "moon starer"),
("hello", "world"),
("A", "a")
]
for str1, str2 in test_cases:
result = is_anagram(str1, str2)
print(f"'{str1}' and '{str2}': {result}")
'listen' and 'silent': True 'The Eyes' and 'They See': True 'astronomer' and 'moon starer': True 'hello' and 'world': False 'A' and 'a': True
Conclusion
Using collections.Counter() method is an efficient way to check if two strings are anagrams. It automatically counts character frequencies and allows direct comparison using the equality operator, avoiding manual character counting.
---