
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
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
- Related Articles
- Anagram checking in Python program using collections.Counter()
- Using Counter() in Python 3.x. to find minimum character removal to make two strings anagram
- Anagram Substring Search using Python
- Using Set() in Python Pangram Checking
- Valid Anagram in Python
- An Anagram I Am in Python
- Count frequencies of all elements in array in Python using collections module
- Decimal counter using logic controller
- Python Program for Anagram Substring Search
- Python counter and dictionary intersection example
- Counter Size and Counter Overflow
- Making a simple counter app using request.session in Django
- Program to find length of longest anagram subsequence in Python
- Creating Animated Counter using HTML, CSS, and JavaScript
- How to create a simple counter Using ReactJS?
