views:

68

answers:

2

I am working on this small little piece in python and when I run it, It never gets past the print 'c' line and is stuck on the while loop. What am I doing wrong? link to text file: http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip

enter code here
import sys
import random

inp = open('5desk.txt', 'r')
lis = inp.readlines()
inp.close()
print lis

def proc():

 a = raw_input('What are the scrambled letters? ')
 copy = list(a)
 print a
 print copy
 if a in lis:
  print a, ' is a word'
 elif a not in lis:
  print 'c'
  while copy not in lis:
   random.shuffle(copy)
  print 'd'


 print "A word that ", a, " might equal is:\n", copy


if __name__ == "__main__":
 proc()
+1  A: 

Perhaps you meant this instead:

while copy in lis:

Either way there is no guarantee that rearranging the letters will eventually create a word that either is or is not in the list. In particular if the input contains only one letter then the shuffle will have no effect at all. It might be better to iterate over all the permutations in a random order, and if you reach the end of the list break out of the loop with a error.

Mark Byers
Well, every time I tried it I used a word from the list. The reason for the not in lis is because It will shuffle until it hits a word in the list.
a sandwhich
Nevermind, I wrote my own permutation function. Sorry
a sandwhich
+1  A: 

readline() and readlines() keep the trailing newline from each line of the input; raw_input() strips newlines. Thus there's never a match.

When reading input from external sources, it's often a good idea to use the strip() function to clean things up - by default, it removes whitespace from each end of its input.

Try:

lis = [line.strip() for line in inp.readlines()]
Russell Borogove
I tried this and the recognition part worked, it is still having trouble with the shuffling. How would I apply itertools.permutations() to this? I tried earlier but was unable to.
a sandwhich
The possibly-tricky bit with itertools.permutations is that if you give it a string, it returns you tuples of individual characters, which you then need to fuse back into strings with "".join() or similar.
Russell Borogove