Anagram checking in Python using collections.Counter()
Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other.
Examples:
Input : str1 = “abcd”, str2 = “dabc” Output : True Input : str1 = “abcf”, str2 = “kabc” Output : False
This problem has existing solution please refer Check whether two strings are anagram of each other link. We will solve this problem in python in a single line using collections.Counter() module.
# Python code to check if two strings are # anagram from collections import Counter def anagram(input1, input2): # Counter() returns a dictionary data # structure which contains characters # of input as key and their frequencies # as it's corresponding value return Counter(input1) = = Counter(input2) # Driver function if __name__ = = "__main__" : input1 = 'abcd' input2 = 'dcab' print anagram(input1, input2) |
Output:
True
How dictionary comparison works in python ?
If we have two dictionary data structures in python dict1 = {‘a’:2,’b’:3,’c’:1} and dict2 = {‘b’:3,’c’:1,’a’:2} and we compare both of them like dict1=dict2 then it will result True. In python ordinary dictionary data structure does not follow any ordering of keys, when we compare two dictionaries then it compares three checks in order number of keys (if they don’t match, the dicts are not equal), names of keys (if they don’t match, they’re not equal) and value of each key (they have to be ‘==’, too).
This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Recommended Posts:
- Using Set() in Python Pangram Checking
- Python | Checking triangular inequality on list of lists
- Python | Checking if starting digits are similar in list
- Python sorted() to check if two strings are anagram or not
- Python Dictionary | Check if binary representations of two numbers are anagram
- Python Counter to find the size of largest subset of anagram words
- Using Counter() in Python to find minimum character removal to make two strings anagram
- Pangram Checking
- Online algorithm for checking palindrome in a stream
- Check whether two strings are anagram of each other
- Check if any anagram of a string is palindrome or not
- Count of total anagram substrings
- Longest Common Anagram Subsequence
- Longest common anagram subsequence from N strings
- Check if binary representations of two numbers are anagram