[Tutor] anagram solving algorithm
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Thu Sep 30 21:00:48 CEST 2004
On Thu, 30 Sep 2004, Max Russell wrote:
> I'm going to sort the input word (i.e the anagram) then get all words of
> equal length to the anagram, sort them, then do a match. I'll return the
> original words (unsorted) for all those that match.
Hi Max,
Yup, that sounds exactly right.
One more trick to make this really fast is to do the letter-sorting on
your whole dictionary of words way in advance, even before getting the
input word
If you this preparation early on, and keep a separate "word -> sorted
word" file, then the anagram check becomes an exact-matching problem. And
Python dictionaries are designed to make exact matching fast:
###
>>> word_entries = { 'one' : 1,
... 'two' : 2,
... 'three' : 3 }
>>> 'one' in word_entries
True
>>> 'five' in word_entries
False
>>> word_entries['three']
3
###
Hope this helps!
More information about the Tutor
mailing list