猜测1到100之间的数字

时间:2018-01-27 00:32:15

标签: python

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

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变量,以便程序知道保持在该范围内?

2 个答案:

答案 0 :(得分:1)

让我们回顾你的条件。我们要做的是根据程序收到的答案重新定义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基于间隔获得ans = (high + low)//2

总的来说,这给了

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")

答案 1 :(得分:0)

计算新间隔时算法略有错误。这是更正后的代码:

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
        ans = (high + low) // 2
    elif check_ans == 'l':
        low = ans
        ans = (high + low) // 2
    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")