Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't group by anagram correctly

I wrote a python function to group a list of words by anagram:

def groupByAnagram(list):
    dic = {}
    for x in list:
        sort = ''.join(sorted(x))

        if sort in dic == True:
            dic[sort].append(x)
        else:
            dic[sort] = [x]

    for y in dic:
        for z in dic[y]:
            print z

groupByAnagram(['cat','tac','dog','god','aaa'])

but this only returns:

aaa

god

tac

what am I doing wrong?

like image 890
Jackery Xu Avatar asked Dec 25 '22 09:12

Jackery Xu


2 Answers

if sort in dic == True:

Thanks to operator chaining, this line is equivalent to

if (sort in dic) and (dic == True):

But dic is a dictionary, so it will never compare equal to True. Just drop the == True comparison entirely.

if sort in dic:
like image 155
Kevin Avatar answered Jan 08 '23 00:01

Kevin


remove the "== True" in your if clause. You can just check with sort in dic.

change the if-clause to:

if sort in dic:

and everything works as expected.

You can also remove the if-clause by using the default dict of the collections package. This way you do not have to check if you have to create a new list for your dict, each time.

import collections
def groupByAnagram2(word_list):
    dic = collections.defaultdict(list)
    for x in word_list:
       sort = ''.join(sorted(x))
       dic[sort].append(x)

    for words in dic.values():
        for word in words:
            print word
like image 24
A. L. Avatar answered Jan 08 '23 00:01

A. L.