对于某些背景:MasterMind®是由Mordechai Meirovitz在1970年代早期发明的代码破解游戏。在这个游戏中, 一个玩家 - 代码大师 - 负责生成由四种颜色序列组成的代码。一个 第二个玩家 - 代码破坏者 - 试图猜测代码。每次猜测后,代码大师提供 关于猜测的反馈。具体来说,代码主机将告诉代码断路器有多少颜色是正确的 以及有多少颜色处于正确的位置。代码破坏者继续猜测代码直到他们 能够成功破解代码。代码破坏者的“得分”是它需要休息的猜测次数 代码。
该计划的目标是:
我只有自信地完成了第1步和第1步。 2.我的问题是我如何获得isValidGuess
函数来确定只有validColors
存在。正如现在所写,该函数没有包含validColors
参数,我不完全确定原因。对于每个函数,都会简要说明函数应该做什么。
-Note-我不希望有人为我编写完整的代码,只是为了帮助我使用isValidGuess
函数。
import random
validColors = ["R", "G", "B", "Y", "O", "P"]
def generateCode(validColors):
#input: takes a string that represents validColors
#action: builds a string of length 4; each character is picked at random
# from the validColors
#return: a string of length 4 representing the codemaster's secretCode
secretCode = random.sample(validColors, 4)
return secretCode
def isValidGuess(guess, validColors):
#input: guess and validColors as strings
#action: ensures that the guess is the right length and only contains
# valids colors
#return: boolean value to isValidGuess
isValidGuess = False
if len(guess) != 4:
print("Invalid, guess again.")
elif len(guess) == 4:
isValidGuess = True
return isValidGuess
#def correctLocationCount(secretCode, guess):
#input: secretCode and guess as strings
#action: character by character comparison of the two strings and
# updates a counter every time they match
#return: the counter
#def correctColorCount(secretCode, guess, validColors):
#input: secretCode, guess, and valid colors as strings
#action: looks at each valid color and counts how many times that color
# appears in the code and how many times it appears in the guess
# Compare these counts to determine how many colors were guessed
#return: the count
def masterMind():
generateCode(validColors)
guess = input("What is your guess: ")
result = isValidGuess(guess, validColors)
while result == False:
guess = input("What is your guess: ")
result = isValidGuess(guess, validColors)
答案 0 :(得分:0)
您可以检查code
中的每种颜色是否也在validColors
中。在Python中最惯用的方法是使用带有生成器表达式的内置all
函数:all(color in validColors for color in guess)
。
另一种方法(新程序员可能更容易理解)是使用显式循环:
for color in guess:
if color not in validColors:
# do whatever is appropriate for an invalid color here (e.g. return False)
您可能需要撤消当前isValidGuess
变量的逻辑(默认为True
,如果猜测无效,则重置为False
)。或者你可以在发现无效的时候立即删除那个变量而只是return False
(如果没有任何证据被取消资格,那么在函数末尾会return True
。)
请注意,我不会在猜测中检查重复的颜色。如果不允许这样做,您可能需要单独检查它,可能使用set
。如果你也将validColors
放入一个集合中,你可以用一个非常紧凑的表达式检查所有内容:
def isValidGuess(guess, validColors):
valid_set = set(validColors) # if validColors was already a set this would be unnecessary
guess_set = set(guess)
return len(guess) == len(guess_set) == 4 and guess_set.issubset(valid_set)