开发者

python app gets stuck on shuffle and loop

I am working on this small litt开发者_JS百科le 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()


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()]


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜