Last active
December 19, 2015 19:18
-
-
Save sahands/6004753 to your computer and use it in GitHub Desktop.
Interview Question: Grouping Word Anagrams (Facebook)
This file contains hidden or 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
import collections | |
def sort_hash(word): | |
return ''.join(sorted(word)) | |
def count_letters_hash(word): | |
d = collections.defaultdict(int) | |
for c in word: | |
d[c] += 1 | |
return tuple(d.items()) | |
def group_anagrams(words, pre_hash_function): | |
result = {} | |
for w in words: | |
s = pre_hash_function(w.lower()) | |
if s in result: | |
result[s] |= {w} | |
else: | |
result[s] = {w} | |
return result.values() | |
#usage: | |
>>> group_anagrams(['tsar', 'rat', 'tar', 'star', 'tars', 'cheese'], sort_hash) | |
[set(['tars', 'tsar', 'star']), set(['cheese']), set(['rat', 'tar'])] | |
>>> group_anagrams(['tsar', 'rat', 'tar', 'star', 'tars', 'cheese'], count_letters_hash) | |
[set(['tars', 'tsar', 'star']), set(['cheese']), set(['rat', 'tar'])] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment