【发布时间】:2020-10-01 18:22:16
【问题描述】:
我是 Python 新手。我正在尝试编写一个小游戏,要求最终用户从 1 到 1000 中选择一个数字并将其保留在他们的脑海中(该数字未提供给程序)。该程序应该能够在 10 次猜测中找到数字。像往常一样,我走错了路。我的程序大部分时间都在工作,但有时它在 10 次以下的猜测中找不到数字。这是我的代码:
# script to guess a user's number between 1 and 1000 within 10 guesses
# import random so we can use it to generate random numbers
from random import randint
# Variables
lowerBound = 1
upperBound = 1000
numGuesses = 1
myGuess = 500
failed = False
# Welcome Message
print("#####################################################################################################"
"\n# #"
"\n# Please think of a number between 1 and 1000. I will attempt to guess the number in 10 tries. #"
"\n# #"
"\n#####################################################################################################")
while numGuesses <= 10:
# if the lower and upper bounds match we've found the number
if lowerBound == upperBound:
print(f"\nYour number is {str(lowerBound)}. It took me '{str(numGuesses)} guesses!")
break
print(f"\nIs the number {str(myGuess)}? If correct, type CORRECT. If low, type LOW. If high, type HIGH.")
# uncomment for var output
# print(f"\nGuesses = {str(numGuesses)}\nLower bound = {str(lowerBound)}\nUpper bound = {str(upperBound)}")
userFeedback = input("\nResponse: ").upper()
if userFeedback == 'HIGH':
print(f"\nGuess #{str(numGuesses)} was too high")
if numGuesses == 10:
failed = True
break
upperBound = myGuess - 1
myGuess = randint(lowerBound, upperBound)
elif userFeedback == 'LOW':
print(f"\nGuess #{str(numGuesses)} was too low")
if numGuesses == 10:
failed = True
break
lowerBound = myGuess + 1
myGuess = randint(lowerBound, upperBound)
elif userFeedback == 'CORRECT':
print(f"\nYour number is {str(myGuess)}! It took me {str(numGuesses)} guesses!")
break
numGuesses += 1
if failed:
print(f"\nMy final guess of {str(myGuess)} was not correct. I wasn't able to guess your number in 10 tries.")
(现在)似乎很清楚,我削减数字的方式行不通。本来想问是不是500,低了就问是不是250,再低就问是不是125,以此类推。如果更高,请询问是否是 750、875 等。这是正确的方法吗?
我考虑这个问题太久了,我相信我已经熟透了。谢谢!
【问题讨论】:
-
下次猜测时不要使用随机数。使用
(upperBound - lowerBound) / 2。 -
不要随机使用!!!这一切都取决于机会
-
你原来的计划是正确的。你为什么用随机数代替?
-
@PeterM。如果我对此有答案就好了。 :) 我会尝试转换它。有没有人有这种方法的例子?
-
myGuess = int((upperBound-lowerBound)/2)