Anagrams using Python

Python can be an elegant language. This is an example – a Python function that finds the anagrams for a supplied word. For the word dictionary I found one in OS X at /usr/share/dict/words.

def anagrams(wordIn):
    f=open('/usr/share/dict/words')                                                                                                                                                                                 
    ana=dict()
    for word in f.readlines():
        ana.setdefault(''.join(sorted(word.rstrip())),[]).append(word.rstrip())
    return ana.get(''.join(sorted(wordIn)))
>>> anagrams("cat")
['act', 'cat']
>>> 
This entry was posted in programming and tagged , , . Bookmark the permalink.

2 Responses to Anagrams using Python

  1. Alex Benke says:

    very elegant.

    one tip, for memory efficiency and simplicity, you can do the following, which reads one line at a time directly from the file, rather than creating a whole list (as in readlines).

    “for word in f:”

    in profiling my words file, that saves about 30MB of RAM (about 20%).

    one more thing, instead of “if wordsin!=None:”, you can do “if wordsin:”, which I think is more pythonic.

  2. Joe says:

    Word Maker Scrabble works good for this type of thing.

Leave a Reply

Your email address will not be published. Required fields are marked *