Skip to content

Instantly share code, notes, and snippets.

@goldsmith
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goldsmith/b24aaba5d0c11a9ef44e to your computer and use it in GitHub Desktop.
Save goldsmith/b24aaba5d0c11a9ef44e to your computer and use it in GitHub Desktop.
Write a program that takes a list of words and groups together the anagrams.
"""
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"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment