我想制作一个程序,要求用户考虑0
和100
之间的数字并尝试猜测。
所以这是我目前的代码:
k = raw_input('Think about a number between 0 and 100. (Enter/Return?): ')
x = 'a'
i = 100
if k == 'Enter':
i = i/2
while x != 'correct':
print 'the number is:', i
x = raw_input('is this the number? (bigger,smaller,correct): ')
if x == 'smaller':
i = i/2
elif x == 'bigger':
i = i + i/2
elif x == 'correct':
print 'Yupiiii!!'
else:
print 'Invalid answer'
我对该计划的主要问题是我无法限制其猜测"范围。
例如:如果它显示50
并且我说它更大会猜测75
,那么如果我说更小则会猜测37
。 37
不是50
和75
之间的数字;如何在这段时间内猜出一个数字?
如果我继续说'bigger'
,它也会超过100。
有什么建议吗?
答案 0 :(得分:3)
这是一个简单的实现(使用-1
代表更低版本,0
代表更高版本,1
代表更高版本),专注于如何跟踪有效的输入范围:
def get_int_input(prompt, min_=None, max_=None):
"""Take valid input from the user.
Notes:
Valid input is an integer min_ <= input <= max_. By default,
no limits are applied.
"""
...
def guess_my_number(min_=0, max_=100):
"""Guess the number the user is thinking of."""
print "Think of a number between {} and {}.".format(min_, max_)
prompt = "Is it {}? "
while True:
guess = min_ + ((max_ - min_) // 2) # guess the middle of the range
result = get_int_input(prompt.format(guess), -1, 1)
if result > 0:
min_ = guess # must be bigger than guess
elif result < 0:
max_ = guess # must be smaller than guess
else:
break # done
在游戏中:
>>> guess_my_number()
Think of a number between 0 and 100.
Is it 50? -1
Is it 25? 1
Is it 37? 1
Is it 43? -1
Is it 40? 1
Is it 41? 1
Is it 42? 0
请注意,制作min_
和max_
参数可让您轻松提出不同的问题:
>>> guess_my_number(1, 10)
Think of a number between 1 and 10.
Is it 5? 1
Is it 7? 0
答案 1 :(得分:0)
您需要跟踪数字可能在的范围的两端,而不仅仅是顶部。