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?
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With