anagram finder / dict mapping question
Jerry Hill
malaclypse2 at gmail.com
Thu May 8 22:31:06 EDT 2008
On Thu, May 8, 2008 at 7:52 PM, dave <squareswallower at 1ya2hoo3.net> wrote:
> I got it! Thanks for all your help!!! Please tell me what you think:
Here's yet another version of the same thing, using defaultdicts and
sets. This way we don't have to test for membership in either the
dictionary or the collection of anagrams. The code is shorter, but no
less readable in my opinion.
from collections import defaultdict
def anafind(words):
"""
Given a sequence of words, return a dictionary with groups
of letters as keys and sets of anagrams as values
"""
anagrams = defaultdict(set)
for word in words:
key = ''.join(sorted(word))
anagrams[key].add(word)
return anagrams
if __name__ == "__main__":
wordlist = ['live', 'evil', 'one', 'nose', 'vile', 'neo']
anagrams = anafind(wordlist)
for letters, words in anagrams.items():
print "%s: %s" % (letters, words)
--
Jerry
More information about the Python-list
mailing list