Last active
August 29, 2015 14:03
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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