Python 逻辑帮助:
我正在编写一个游戏,有两个失败条件:
- 组成一个超过 3 个字母的单词。蜜蜂可以,啤酒不行。
- 组成一个无法组成更长单词的单词。斑马可以,斑马不行。
Wordlist 是单词列表,frag 是前一个片段,a 是玩家输入的新字母。因此,frag 可能看起来像“app”,也可能像“l”,具有构成单词 apple 的想法。
def getLoser(frag, a, wordlist):
word = frag + a
if len(word) > 3:
if word in wordlist:
print 'word in wordlist'
return True
else:
for words in wordlist:
if words[:len(word)] == word:
print words,':', word
print 'valid word left'
return False
else:
print words[:len(word)]
print words,':', word
print 'false found'
return True
else:
return False
由于某种原因,当我输入第四个字母时,它会自动转到 for 循环中的 else ,即使当我在交互式跟踪中的虚拟数据上单独测试它时, for 循环中的 if 语句函数工作正常也是如此。
以下是 frag alg 和字母 e 以及单词列表中单词 algebra 的输出。
e
aa
aa:藻类
发现错误
正确
有什么想法吗?
I am writing a game where there are two losing conditions:
- Forming a word longer than 3 letters. Bee is okay, Beer is not.
- Forming a word that can't be made into a longer word. Zebra is okay, Zebras is not.
Wordlist is a list of words, frag is the previous fragment and a is the new letter a player enters. so frag may look like 'app' and a maybe 'l' with the idea of forming the word apple.
def getLoser(frag, a, wordlist):
word = frag + a
if len(word) > 3:
if word in wordlist:
print 'word in wordlist'
return True
else:
for words in wordlist:
if words[:len(word)] == word:
print words,':', word
print 'valid word left'
return False
else:
print words[:len(word)]
print words,':', word
print 'false found'
return True
else:
return False
For some reason when I enter my 4th letter, it automatically goes to the else in the for loop, even when the if statement functions in the for loop works correctly when I test it alone on dummy data in the interactive trail.
Here is output for the frag alg and the letter e with the word algebra in the wordlist.
e
aa
aa : alge
false found
True
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你把事情搞得太复杂了。如果新片段少于3个字母,则自动确定。如果不是,它必须是某个单词的开头并且而不是单词本身才可以。
(可以将上面的两个测试组合成一个条件语句:
但我认为这过于晦涩。)
我无法遵循上面代码的逻辑;它写得相当混乱。 (例如,为什么
words
是一个字符串?)在尝试实现游戏之前,尝试用伪代码编写游戏逻辑——这可能会帮助您理清思路。这是一个更清晰的版本:
You are overcomplicating things. If the new fragment is less than 3 letters, it is automatically OK. If not, it must be the start of some word and not be a word itself to be OK.
(It would be possible to combine the two tests above into one conditional statement:
but I think that is overly obscure.)
I can't follow the logic of your code above; it is rather confusingly written. (Why is
words
a string, for instance?) Try writing the logic of the game in pseudocode before trying to implement it -- that may help you sort out your thoughts.Here's a clearer version: