Question
I feel like my code could be more elegant/more pythonic/faster, but I can't think of too much more to improve. So, I've come to the internet to see what more can be done with standard python.
What my code does
My code counts anagrams for each word in a list of words. For example:
post, spot stop, tops
are four of the words in my list and since all are anagrams of each other, each word should map to the number 4 in a dictionary. Specifically I'm counting the size of the anagram group each word would fit in. The output for a few words would look something like the following then:
{'1-2-3': 1,
'1980s': 1,
'1990s': 1,
...
...
'top': 1,
'topic': 2,
'topics': 1,
'topped': 1,
'tops': 4,
'tory': 2,
'total': 1,
'totals': 1,
'touch': 1,
'tough': 2,
...
...
'zone': 1,
'zones': 1,
'zurich': 1}
My code
from itertools import permutations
from collections import Counter
def get_variants(word):
return map(lambda t: "".join(t), set(permutations(word)))
def count_anagrams(words):
anagram_counts = {w: 1 for w in words}
word_counters = list(map(Counter, words))
for i, (word, counter) in enumerate(zip(words, word_counters)):
for other_word, other_counter in zip(words[i+1:], word_counters[i+1:]):
if counter == other_counter:
anagram_counts[word] += 1
anagram_counts[other_word] += 1
return anagram_counts