python 应用程序卡在随机播放和循环上
我正在 python 中处理这个小片段,当我运行它时,它永远不会超过 print 'c' 行并卡在 while 循环上。我做错了什么?链接到文本文件: 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()
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
readline() 和 readlines() 保留输入每一行的尾随换行符; raw_input() 去除换行符。因此永远不会匹配。
从外部源读取输入时,通常最好使用 strip() 函数来清理内容 - 默认情况下,它会删除输入两端的空格。
尝试:
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:
也许您的意思是这样的:
无论哪种方式,都不能保证重新排列字母最终会创建一个在列表中或不在列表中的单词。特别是如果输入仅包含一个字母,则随机播放将根本不起作用。最好以随机顺序迭代所有排列,如果到达列表末尾,则因错误而跳出循环。
Perhaps you meant this instead:
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.