这是我的代码,计算机应该猜测1到100之间的数字。计算机的猜测应该减少或增加前一次猜测的一半。第三次通过循环只会更高,它会中断,或者如果我说更低,它会打破。两种方式,它将停止添加其猜测并将先前的猜测除以2,而不是将先前的猜测除以前两次猜测。即,而不是50 +(50/2)= 75我的代码确实50/2 = 25.所以它在更高处突破的是87,而不是加上之前猜测的一半,这将是6,它将87除以2等于43.(我现在已经编辑了这个问题,除了需要帮助的地方,代码和一切都应该有用。谢谢)
pcguess = 50
useranswer = 50
print("Wanna see a magic trick?")
print("Please think of a random number between 1 and 100.")
print("Now that you have written down your number")
print("I will guess it in ten guesses or less.")
a = print("My first guess is", pcguess)
tries = 0
while tries < 100000:
newguess = pcguess//2
b = input("Was that your number?")
if b == "no":
tries += 1
c = input("Is your number higher or lower than my guess?")
if c == "lower":
print("Then my next guess is:")
print(useranswer - newguess )
useranswer = pcguess - newguess
pcguess = newguess
tries += 1
elif c == "higher":
print("Then my next guess is:")
print(useranswer + newguess)
useranswer = pcguess + newguess
pcguess = newguess
tries += 1
if b == "yes":
print("I got it in", tries, "tries!")
break
答案 0 :(得分:3)
我会在代码中更改的第一件事是增加tries
变量的位置。在当前的while循环中,每次执行while循环时都会递增一次,然后在执行任何if
语句之后再递增一次。这意味着每次迭代,您的尝试次数都会增加2而不是1.那么为什么不在循环开始时只增加tries
一次呢?
其次,你的useranswer
变量不能成为你期望的原因仅仅是因为你错误地更新了它。例如
if c == "lower":
print("Then my next guess is:")
print(useranswer - newguess )
useranswer = pcguess - newguess # WRONG
pcguess = newguess
由于您要更新useranswer
,因此应useranswer = useranswer + newguess
或更简洁useranswer += newguess
为其他if语句执行此操作(您的猜测高于计算机猜测的位置)
第三。这更多的是样式问题,但是你的while
循环条件应该更准确(即,因为你告诉用户你将在10次或更少的尝试中猜测它们的数量,你的循环条件是否真的需要{{ 1}}?
答案 1 :(得分:2)
您需要根据用户&#34;更高&#34; /&#34;更低&#34;缩小可能的数字范围。响应。因此,您应该将下限和上限存储为变量,并在获得响应时进行调整。像这样:
lower = 0
upper = 100
while lower < upper:
guess = (lower+upper)//2
print("My guess is ", guess)
# Find out if the correct answer is higher or lower than this guess
if the correct answer is higher:
lower = guess + 1 # This gives a new lower bound
if the correct answer is lower:
upper = guess - 1 # This gives a new upper bound