lily
lily

Reputation: 1

how to use python to produce a group of anagram with a given list

for example :giving a list

['car','bed','stop','pots','arc','tops','z','z','rac','deb'] 

then with the function: produce

[['arc', 'car', 'rac'], ['bed', 'deb'], ['pots', 'stop', 'tops'], ['z', 'z']] 

Upvotes: 0

Views: 383

Answers (1)

John La Rooy
John La Rooy

Reputation: 304355

Seems to be taken from this assigment, but the OP doesn't specify the "no builtin sort constraint, so...

>>> from collections import defaultdict
>>> d=defaultdict(list)
>>> words = ['car','bed','stop','pots','arc','tops','z','z','rac','deb']
>>> for w in words:
...   d[''.join(sorted(w)].append(w)
... 
>>> d.values()
[['bed', 'deb'], ['car', 'arc', 'rac'], ['z', 'z'], ['stop', 'pots', 'tops']]

Upvotes: 3

Related Questions