input: [\'abc\', \'cab\', \'cafe\', \'face\', \'goo\']
output: [[\'abc\', \'cab\'], [\'cafe\', \'face\'], [\'goo\']]
The problem is simple: it grou
The readable version:
from itertools import groupby
from operator import itemgetter
def norm(w):
return "".join(sorted(w))
words = ['abc', 'cba', 'gaff', 'ffag', 'aaaa']
words_aug = sorted((norm(word), word) for word in words)
grouped = groupby(words_aug, itemgetter(0))
for _, group in grouped:
print map(itemgetter(1), group)
The one-liner:
print list(list(anagrams for _, anagrams in group) for _, group in groupby(sorted(("".join(sorted(word)), word) for word in words), itemgetter(0)))
Prints:
[['aaaa'], ['abc', 'cba'], ['ffag', 'gaff']]