python 应用程序卡在随机播放和循环上

发布于 2024-09-25 10:59:56 字数 693 浏览 2 评论 0原文

我正在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

痴情 2024-10-02 10:59:56

readline() 和 readlines() 保留输入每一行的尾随换行符; raw_input() 去除换行符。因此永远不会匹配。

从外部源读取输入时,通常最好使用 strip() 函数来清理内容 - 默认情况下,它会删除输入两端的空格。

尝试:

lis = [line.strip() for line in inp.readlines()]

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()]
何必那么矫情 2024-10-02 10:59:56

也许您的意思是这样的:

while copy in lis:

无论哪种方式,都不能保证重新排列字母最终会创建一个在列表中或不在列表中的单词。特别是如果输入仅包含一个字母,则随机播放将根本不起作用。最好以随机顺序迭代所有排列,如果到达列表末尾,则因错误而跳出循环。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文