开发者

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

开发者 https://www.devze.com 2023-03-20 22:32 出处:网络
for example :giving a list [\'car\',\'bed\',\'stop\',\'pots\',\'arc\',\'tops\',\'z\',\'z\',\'rac\',\'deb\']

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']] 
开发者_开发百科


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']]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号