Skip to content

Instantly share code, notes, and snippets.

@rohit-jamuar
Last active August 29, 2015 14:04
Show Gist options
  • Save rohit-jamuar/cc1dffc87c43dd6439c1 to your computer and use it in GitHub Desktop.
Save rohit-jamuar/cc1dffc87c43dd6439c1 to your computer and use it in GitHub Desktop.
Groups anagrams in lists (without sorting)
#!/usr/bin/python
from prime_number_generator import prime_number_generator
from operator import mul
from string import lowercase
P_GEN = prime_number_generator()
REF = { elem : P_GEN.next() for elem in lowercase }
def anagram_grouper(input_list):
'''
Groups anagrams in lists.
Time complexity : O(n*k) where n is size of 'input_list' and
k is the length of longest word.
'''
final = {}
for elem in input_list:
char_prod = reduce(mul, [REF[char] for char in elem.lower()])
final[char_prod] = final.get(char_prod, []) + [elem]
for key in final:
print final[key]
if __name__ == '__main__':
anagram_grouper(['abc', 'asfsadad', 'bcs', 'bca'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment