[英]How to code so the program finds multiple instances - Python
我有以下代码:
Words = ['python','candy', 'banana', 'chicken', 'pizza', 'calculus',
'cheeseburger', 'binder', 'computer', 'pencil', 'school'
'artist', 'soccer', 'tennis', 'basketball', 'panda',
'zebra', 'horse', 'cereal', 'alphabet', 'understand']
number = raw_input('Enter a 1 through 20: ')
x = list()
find = list(Words[int(number)-1])
notherword = list(Words[int(number)-1])
l = list(len(find)*'_')
print 'Your word is', len(find)*'_ '
playing = True
while playing:
letter = raw_input('Please pick a letter ')
if letter in find:
a = find.index(str(letter))
l[int(a)] = letter
q = (' ')
j = q.join(l)
print j
find[a] = ('_')
if l == notherword:
print 'You win!!!'
playing = False
else:
print 'Strike ' +str(len(x)+1) +str('.') +str(' Not a letter in the word')
x.append(letter)
if len(x) > 4:
print 'Game Over x('
playing = False
这是一个子手游戏。 您首先选择一个数字,然后该数字与单词相对应,然后开始执行man子手游戏。 但是,当我执行“香蕉”一词时,它只会找到第一个a,而找不到另一个a。 我该如何编码,以便它可以一次找到多个实例,从而使其运行正常?
使用更新的代码进行编辑
一个简单的解决方案是将找到的字母替换为其他字母,这样就不会出现两次。 您可以使用列表理解来获取给定字母的所有索引:
if letter in find:
# use a list comprehension to get the index of all occurrences of a given letter
indexes = [i for i, char in enumerate(find) if char == letter]
# update found and l accordingly
for i in indexes:
find[i] = None
l[i] = letter
然后检查他们是否赢了,您可以改为:
if '_' not in l:
print 'You win!!!'
您还需要在while
循环之外创建x
,而不是在玩家每次猜错时都重新创建x
,这样玩家实际上就可能输掉(您也可以while True
和break时执行,而不是使用playing
变量):
x = list()
while True:
...
else:
print 'Not a letter in the word'
x.append(letter)
if len(x) > 4:
print 'Game Over'
break
顺便说一句,您不需要在循环中使用str
或int
。 另外''.join()
是一个通用的Python习惯用法,您应该改用它。 考虑到以上因素,这是修订版:
Words = ['python','candy', 'banana', 'chicken', 'pizza', 'calculus',
'cheeseburger', 'binder', 'computer', 'pencil', 'school'
'artist', 'soccer', 'tennis', 'basketball', 'panda',
'zebra', 'horse', 'cereal', 'alphabet', 'understand']
number = raw_input('Enter a 1 through 20: ')
find = list(Words[int(number)-1])
l = list(len(find)*'_')
x = list()
print 'Your word is', len(find)*'_ '
while True:
letter = raw_input('Please pick a letter ')
if letter in find:
indexes = [i for i, char in enumerate(find) if char == letter]
for i in indexes:
find[i] = None
l[i] = letter
print ' '.join(l)
if '_' not in l:
print 'You win!!!'
break
else:
print 'Not a letter in the word'
x.append(letter)
if len(x) > 4:
print 'Game Over'
break
您必须使用循环来依次匹配每个a:
while playing:
letter = raw_input('Please pick a letter ')
while letter in find:
a = find.index(letter)
# Clear the letter so we can match the next instance.
find[a] = None
l[a] = letter
q = (' ')
j = q.join(l)
print j
if l == find:
print 'You win!!!'
playing = False
else:
....
[这不是通常要做的所有事情,但是您可以在Python中结合使用else。 ]
同样,您应该在游戏循环上方设置x = list(),就这样,您永远不会输。
你应该更换这个
if letter in find:
a = find.index(str(letter))
l[int(a)] = letter
有了这个
letter_in_word = False
for a,c in enumerate(find):
if c == letter:
l[a] = letter
letter_in_word = True
if letter_in_word:
...
else:
...
代替
a = find.index(str(letter))
l[int(a)] = letter
尝试这个
[l.__setitem__(pos, letter) for pos in range(len(find)) if find[pos]==letter]
基本上,如果所选的字母位于需要找到的单词中的那个位置,则对单词进行迭代将其设置为所选的字母。
我通常不会只为某人编写代码,但是有时这是说明各种技术的最佳方法。 请仔细研究。 请注意,如果我实际上是在编写此代码,则其中将不会包含任何注释。 这些技术是标准的。
# Let's wrap the "main" code in a function for cleanliness.
def main():
words = [
'python','candy', 'banana', 'chicken', 'pizza', 'calculus',
'cheeseburger', 'binder', 'computer', 'pencil', 'school'
'artist', 'soccer', 'tennis', 'basketball', 'panda',
'zebra', 'horse', 'cereal', 'alphabet', 'understand'
]
import random
word = random.choice(words)
# Instead of using a list of characters for what's been
# guessed, a string will work fine. We can iterate over it
# the same way.
guessed = '_' * len(word)
failures = '' # used to be 'x'. Use descriptive names.
# To break out of a loop, we can use the 'break' keyword.
# So we don't really need a separate variable to control the loop.
# We want to show status every time through the loop, so we put that
# inside the loop.
while True:
print guessed
# Note the idiomatic way we use to intersperse spaces into the word.
print 'Not in the word:', ' '.join(failures)
letter = raw_input('Please pick a letter: ')
# We use the following trick to update the guess status:
# 1) We'll create a second string that contains the guessed
# letter in each place where it should appear.
# 2) If that string differs from the old guess, then we
# must have guessed a letter correctly. Otherwise, the letter
# is not in the word.
# We take pairs of letters from `word` and `guessed` using the
# zip() function, and use the letter from the word if it's matched,
# and otherwise keep the letter from the old guess. `''.join` joins
# up all the chosen letters to make a string again.
new_guess = ''.join(
w if w == letter else g
for (w, g) in zip(word, guessed)
)
if new_guess == word:
print 'You win!!!'
break
elif new_guess != guessed:
print "Yes, '%s' is in the word." % letter
else:
# Instead of having the ugly '+1' in the logic for counting misses,
# just count the misses *after* processing this one. Also note how
# the string formatting works.
failures += letter
print "Strike %d. '%s' is not in the word." % (len(failures), letter)
if len(failures) > 4:
print 'Game Over x('
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.