gpt4 book ai didi

python - 猜测 1 到 100 之间的数字

转载 作者:太空宇宙 更新时间:2023-11-03 14:11:22 27 4
gpt4 key购买 nike

程序应该从用户那里获取一个整数,并使用二分搜索来猜测该整数是什么。

user_num = (int(input("Please think of a number between 0 and 100! ")))
low = 0
high = 100
ans = (high + low)//2

while True:
print("is your secret number " + str(ans))
check_ans = input("""enter 'h' to indicate if the guess is too high.
enter 'l' to indicate if the guess is too low.
enter 'c' if I guessed correctly.""")

if check_ans == 'h':
high = ans//2
ans = high

elif check_ans == 'l':
low = ans*2
ans = low

elif check_ans == 'c' and check_ans == user_num:
print("Game over. Your secret number was: " + str(ans))
break

else:
print("I do not understand your command")

我相信我遇到的问题发生在 while 循环中。我需要程序知道一旦达到阈值就何时停止。假设我的整数是 34,一旦我点击“h”作为输入,它就会下降到 25。现在如果我点击“l”,它就会跳回 50。

我想我的问题是如何更新 ans 变量以便程序知道保持在该范围内?

最佳答案

我们来看看你的条件。我们想要做的是根据程序收到的答案重新定义 lowhigh

if check_ans == 'h':
# We know that ans is lower, so we set our higher bound to slightly below ans
high = ans - 1

elif check_ans == 'l':
# We know that ans is higher, so we set our lower bound to slightly above ans
low = ans + 1

然后在循环开始时,您希望通过执行 ans = (high + low)//2 来根据间隔获取 ans

总的来说,这给出了

user_num = (int(input("Please think of a number between 0 and 100! ")))

low = 0
high = 100

while True:
ans = (high + low)//2

print("is your secret number " + str(ans))
check_ans = input("""
enter 'h' to indicate if the guess is too high.
enter 'l' to indicate if the guess is too low.
enter 'c' if I guessed correctly.""")

if check_ans == 'h':
high = ans - 1

elif check_ans == 'l':
low = ans + 1

elif check_ans == 'c' and check_ans == user_num:
print("Game over. Your secret number was: " + str(ans))
break

else:
print("I do not understand your command")

关于python - 猜测 1 到 100 之间的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48471434/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com