+

Checking an anagram in Python using collection.Counter ()

Examples:

 Input: str1 = “abcd”, str2 = “dabc” Output: True Input: str1 = “abcf”, str2 = “kabc” Output: False 

This problem has an existing solution, please refer.  collection.Counter () module .

# Python code to check for two lines
# anagram

from collections import Counter

 

def anagram (input1, input2):

 

  # Counter () returns dictionary data

  # structure that contains characters

  # input as key and their frequency

# as appropriate value

return Counter (input1) = = Counter (input2)

 
# Driver function

if __ name__ = = "__ main__" :

input1 = `abcd`

input2 = `dcab`

  print anagram (input1, input2)

Output:

 True 

How does dictionary comparison work in python?
If we have two dictionary data structures in python dict1 = {& # 39; a & # 39 ;: 2, & # 39; b & # 39 ;: 3, & # 39; c & # 39 ;: 1} and dict2 = {& # 39; b & # 39 ;: 3, & # 39; c & # 39 ;: 1, & # 39; a & # 39 ;: 2} and we compare them both as dict1 = dict2, then it will be True . In Python, a normal dictionary data structure does not follow the order of the keys, when we compare two dictionaries, then three checks are compared in order of key numbers (if they do not match, the values ​​do not match) , key names ( if they do not match, they are not equal) and the value of each key (they must also be & # 39; == & # 39;) .

This article provided by Shashank Mishra (Gullu) . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you`d like to share more information on the topic discussed above.

Get Solution for free from DataCamp guru