我正在尝试使用二分搜索在python中制作一个猜谜游戏。我的代码是这样的。
print('please think of a number between 1 and 100')
high=100
low=1
guess=int((high+low)/2)
n=input('is your number 50? press y to yes, l to low, h to high ')
while n!='y':
if n=='h':
high=guess
n=input('is your number '+str(guess)+'? press y to yes, l to low, h to high ')
elif n=='l':
low=guess
n=input('is your number '+str(guess)+'? press y to yes, l to low, h to high ')
print()
else:
n=input('wrong input. press y to yes, l to low, h to high ')
print()
guess=int((high+low)/2)
print('game over. i guessed correctly')
但不幸的是,我从这段代码中得不到所需的东西。你介意帮帮我吗?提前致谢
答案 0 :(得分:2)
你应该在你的while循环中向用户显示提示之前更新猜测。
while n!='y':
if n=='h':
high=guess
guess=int((high+low)/2)
n=input('is your number '+str(guess)+'? press y to yes, l to low, h to high ')
elif n=='l':
low=guess
guess=int((high+low)/2)
n=input('is your number '+str(guess)+'? press y to yes, l to low, h to high ')
print()
else:
n=input('wrong input. press y to yes, l to low, h to high ')
print()
答案 1 :(得分:0)
所以问题是你没有更新"猜测"在更改高/低之后但在将其打印给用户之前。
这是修改过的代码。
注意,我还更改了消息的语言,以便在用户键入" h"时更清楚。当他们输入" l"
时print('please think of a number between 1 and 100')
high=100
low=1
guess=int((high+low)/2)
input_options = 'press "y" if yes, "l" if it is lower, "h" if it is higher: '
n=input('is your number '+str(guess)+'? ' + input_options)
while n!='y':
if n=='h':
low=guess
guess=int((high+low)/2)
n=input('is your number '+str(guess)+'? ' + input_options)
elif n=='l':
high=guess
guess=int((high+low)/2)
n=input('is your number '+str(guess)+'? ' + input_options)
else:
n=input('wrong input. ' + input_options)
print('game over. i guessed correctly')
答案 2 :(得分:0)
guess
的更新可能有错误,我的意思是,当猜测值低于预期值时,您应该猜测从当前猜测到之前high
的新值,所以只需更改low
:
if n=='h':
low=guess
guess=int((high+low)/2)
答案 3 :(得分:0)
期望它是一个二元搜索场景,我对优化做了很少的改变。
print('please think of a number between 1 and 100')
high=100
low=1
guess=int(low+(high-low)/2)
n=input('is your number '+str(guess)+'? press y to yes, l to low, h to high ')
while n!='y':
if n=='h':
low=guess
elif n=='l':
high=guess
else:
n=input('wrong input. press y to yes, l to low, h to high ')
guess=int(low+(high-low)/2)
n=input('is your number '+str(guess)+'? press y to yes, l to low, h to high ')
print('game over. i guessed correctly')