""" Write a program that takes a list of words and groups together the anagrams. """ from collections import Counter, defaultdict def group_by(col, hashfn=None): if not hashfn: hashfn = hash # builtin hash group = defaultdict(list) [group[hashfn(e)].append(e) for e in col] return group.values() def anagram_hash(word): return tuple(sorted(Counter(word))) group_by(["hello", "foo", "olleh", "bar", "baz", "arb"], hashfn=anagram_hash) # [["hello", "olleh"], ["foo"], ["bar", "arb"], ["baz"]]