[Tutor] More Pythonesque or a more efficient method
bermanrl at embarqmail.com
Sun Oct 5 19:52:07 CEST 2008
The below script which prints anagrams available for any word available
within a given database. It does work, but it is not very fast. I am
relatively certain there are more Python friendly coding techniques but
I am more concerned with a faster algorithm.
The database item consists of the key; the actual word, and the value,
the size as a string. For example, the word 'myth' is represented as
key= 'myth', value = '4'. I think the slow part of the algorithm is the
script retrieves a list of all database words of length (myth)=4. That's
a lot of words. Each word is sorted and then compared to the alpha
sorted word. When there is a match, that word becomes a part of the
anagram list. Even a very basic look at the word 'myth' shows there are
no anagrams. So, to return an empty list, we have scanned all words in
the database of size 4.
I will be happy to send the first program and the original word file to
anyone who would like to implement the database. I could not attach
the database since that made this post way too large.
Any and all suggestions are most welcome.
##The second program is in a perpetual loop waiting on input. A 'Q '
will terminate the program.
##All input is by string; for example the word 'zygote' without the
quotes is a request for all possible anagrams
##created from all the letters in 'zygote'.
def get_key(d1, value):
return [item for item in d1.items() if item == value]
for items in wordlist:
if items != word:
while Repeat != False:
word_in=str(raw_input('Input a word to build anagrams\nA Q will
quit the program: '))
Repeat = False
if db.has_key(word_in) < 1:
print word_in,' is not in the dictionary\n'
if Anagrams != None:
print 'Anagrams for ',word_in,' are ',Anagrams
print word_in,' has no anagrams.'
if __name__ == '__main__': main()
More information about the Tutor