pythoncounteranagram

How to create an anagram that prints an order of string in python using counter?


I am struggling to create an order of string using counter in python and my program is not printing an order of the given string below.

from collections import Counter, defaultdict  
def checking_anagram(keywords):  
    agrms = defaultdict(list)  
    for i in keywords:  
        hist = tuple(Counter(i).items())  
        agrms[hist].append(i)  
    return list(agrms.values())  
keywords = ("eat","tea","tan","ate","nat","bat","bat")  
print(checking_anagram(keywords)) 

Solution

  • The only real problem you have is your hist line. I don't know what you were trying to do, but that is wrong. What you need to do is sort the letters of each word, and use that as your key:

    from collections import defaultdict  
    def checking_anagram(keywords):  
        agrms = defaultdict(list)  
        for word in keywords:  
            s = ''.join(sorted(word))
            agrms[s].append(word)
        return list(agrms.values())  
    keywords = ("eat","tea","tan","ate","nat","bat")  
    print(checking_anagram(keywords)) 
    

    Output:

    [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat', 'bat']]