If I have a list of strings for example:
[\"car\", \"tree\", \"boy\", \"girl\", \"arc\"...]
What should I do in order to find anagrams in t
here is the impressive solution.
funct alphabet_count_mapper:
for each word in the file/list
1.create a dictionary of alphabets/characters with initial count as 0.
2.keep count of all the alphabets in the word and increment the count in the above alphabet dict.
3.create alphabet count dict and return the tuple of the values of alphabet dict.
funct anagram_counter:
1.create a dictionary with alphabet count tuple as key and the count of the number of occurences against it.
2.iterate over the above dict and if the value > 1, add the value to the anagram count.
import sys
words_count_map_dict = {}
fobj = open(sys.argv[1],"r")
words = fobj.read().split('\n')[:-1]
def alphabet_count_mapper(word):
alpha_count_dict = dict(zip('abcdefghijklmnopqrstuvwxyz',[0]*26))
for alpha in word:
if alpha in alpha_count_dict.keys():
alpha_count_dict[alpha] += 1
else:
alpha_count_dict.update(dict(alpha=0))
return tuple(alpha_count_dict.values())
def anagram_counter(words):
anagram_count = 0
for word in words:
temp_mapper = alphabet_count_mapper(word)
if temp_mapper in words_count_map_dict.keys():
words_count_map_dict[temp_mapper] += 1
else:
words_count_map_dict.update({temp_mapper:1})
for val in words_count_map_dict.values():
if val > 1:
anagram_count += val
return anagram_count
print anagram_counter(words)
run it with file path as command line argument