General
First, a helper function. Given a word list, this returns a dictionary that maps the sorted letters in each word to the words that use all of those letter.
def make_anagram_dict(words):
"""Return dict mapping sorted letters -> [words w/ those letters]
>>> (make_anagram_dict(["act", "cat", "dog", "god"]) ==
... {'dgo': ['dog', 'god'], 'act': ['act', 'cat']})
True
"""
out = {}
for w in words:
sorted_word = "".join(sorted(w))
out.setdefault(sorted_word, []).append(w)
return out
Then, our main function, which uses that to find the most common anagram.
def find_most_anagrams_from_wordlist(wordlist):
"""Given list of words, return the word with the most anagrams."""
# START SOLUTION
all_anagrams_dict = make_anagram_dict(wordlist)
highest_num_anagrams = 0
most_anagrams = None
for w in wordlist:
sorted_word = "".join(sorted(w))
number_anagrams = len(all_anagrams_dict[sorted_word])
if number_anagrams > highest_num_anagrams:
highest_num_anagrams = number_anagrams
most_anagrams = w
return most_anagrams