Cannot group correctly by anagram

I wrote a python function to group the 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:

aah

the God

TAS

what am I doing wrong?

+4
source share
2 answers
if sort in dic == True:

Thanks to the chain of operators, this line is equivalent

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

But dic is a dictionary, so it will never compare with True. Just completely reverse the == True comparison.

if sort in dic:
+9
source

remove "== True" in your if argument. You can just check with sorting in dic.

change the if clause to:

if sort in dic:

and everything works as expected.

if-, . , , dict.

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
+1

Source: https://habr.com/ru/post/1628170/


All Articles