[Tutor] Python Word Unscrambler

Kent Johnson kent37 at tds.net
Fri Jun 23 12:34:50 CEST 2006


Null Mr.Freeman wrote:
> Python Word Unscrambler:
> 
> OK, this is the Python code I'm using to unscramble words but it 
> unscrambles one word at a time, can someone please help me out and tell 
> me how can I improve my code to make it decrypt several words at a time?
> P.S: Another thing is that it prints the solution 4 or 5 times don't 
> know why.

One way to make it work with multiple words would be to put the call to 
main() in a loop. (You might want to rename main() to something like 
unscramble()). Each time through the loop you will be asked for a word 
to unscramble.

I'm not sure why you get the same solution multiple times. If the 
scrambled word has repeated letters that will cause repeated answers 
because you generate all permutations of the letters. One solution would 
be to make a set out of the anagrams of the original word, that will 
remove any duplicates.

You could also use a set instead of a dict to store the word list. And 
don't use dict as the name of a variable, it shadows the name of the 
built-in dict object.

Another approach to solving anagrams is to sort the letters in the 
scrambled word. When you read the dictionary, sort the letters in each 
dictionary word and build a dict that maps sorted words to a list of all 
the words that sort that way. Then you can solve an anagram with a 
single lookup in the dict of sorted words.

HTH,
Kent

> 
> Sorry, I'm very new to Python.
> Please help if you can.
> Thanks a ton!
> ------------------------------------------------------------------------------------------------------------
> 
> CODE
> 
> import string
> 
> def anagrams(s):
>     if s == "":
>         return [s]
>     else:
>         ans = []
>         for an in anagrams(s[1:]):
>             for pos in range(len(an)+1):
>                 ans.append(an[:pos]+s[0]+an[pos:])
>         return ans
> 
> def dictionary(wordlist):
>     dict = {}
>     infile = open(wordlist, "r")
>     for line in infile:
>         word = line.split("\n")[0]
>         dict[word] = 1
>     infile.close()
>     return dict
> 
> def main():
>     anagram = raw_input("Please enter a words you need to unscramble: ")
>     anaLst = anagrams(anagram)
>     diction = dictionary("wordlist.txt")
>     for ana in anaLst:
>         if diction.has_key(ana):
>             print "The solution to the jumble is", ana
> 
> main()
> 
> ------------------------------------------------------------------------------------------------------------
> 
>  
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor




More information about the Tutor mailing list