所以我一直在想办法写一个程序,让电脑猜出我想的数字,而不是用另一种方法猜出电脑选择的数字。它在大多数情况下都是有效的,但是在某些情况下,它会在链上重复数字,即使我之前告诉过它,例如,我正在考虑的值高于“7”。在某些情况下,它还会重复相同的数字,即使我告诉它它的高或低。如果有更有经验的人可以看看这个,告诉我在这些循环中我遗漏了什么,这将有很大帮助。
#computer enters a value x
#lower - computer guesses lower than x
#higher - computer guesses higher than x
#when string "You got it!" - game over
import random
lowBound = 0
highBound = 100
randomNumber = random.randint(lowBound,highBound)
print ("Is it ", randomNumber, " ?")
response = input()
while response != "You got it!":
if response == "higher":
lowBound = randomNumber
randomNumber = random.randint (lowBound, highBound)
print ("Is it ", randomNumber, " ?")
response = input()
elif response == "lower":
highBound = randomNumber
randomNumber = random.randint (lowBound, highBound)
print ("Is it ", randomNumber, " ?")
response = input()
if response == "You got it!":
print ("Woohooo, I'm so bitchin'")
在提到的其他问题中,你的一个问题是:
你正在设置一个新的界限,这是好的,但然后你选择另一个随机数!
你应该做的,是将界限减半,然后从那里向用户询问高低。看看二进制搜索算法。
你的程序仍然可以工作(这里提到的其他更改),但这会在大多数情况下更快地猜出你的号码。
实际上有an example of this game on Wikipedia.
random.randint
是包含的,因此:以及
此外,如果用户没有输入有效的响应,将永远不会再次调用
input()
,程序将挂起在无限循环中。更强大的东西,但不能对付骗子:
random.randint(a, b)
返回一个介于a
和b
之间的数字。生成新的随机数时,应使用random.randint(lowBound+1, highBound-1)
相关问题 更多 >
编程相关推荐