You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python猜数字游戏二分查找范围更新错误求助

Fixing the Binary Search Logic in Your Number Guessing Game

Hey there! Let's work through the issues in your binary search logic and get this number guesser working right.

What's Going Wrong

Your current code breaks the binary search range because you're updating low and high with incorrect calculations:

  • When the user says the guess is too high ('h'), you set high = ans//2—this chops the range way down instead of just setting the upper bound to your current guess (since the secret number must be smaller than ans).
  • When the guess is too low ('l'), low = ans*2 jumps the range back up, completely abandoning the narrow search you started.
  • The win condition check_ans == 'c' and check_ans == user_num is also flawed: check_ans is a string, and user_num is an integer—they'll never match. You just need to trust the user's 'c' input means you guessed right.

Fixed Code

Here's the corrected version with proper binary search behavior:

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

while True:
    print(f"Is your secret number {ans}?")
    check_ans = input("Enter 'h' if the guess is too high, 'l' if too low, 'c' if correct: ").lower()
    
    if check_ans == 'h':
        # Guess was too high—new upper bound is current answer
        high = ans
        ans = (low + high) // 2
    elif check_ans == 'l':
        # Guess was too low—new lower bound is current answer
        low = ans
        ans = (low + high) // 2
    elif check_ans == 'c':
        print(f"Game over. Your secret number was: {ans}")
        break
    else:
        print("I don't understand your command. Please try again.")

Key Fixes Explained

  1. Proper Range Updates:
    • For 'h': Set high = ans (since the secret number is smaller than your guess) then recalculate ans as the midpoint of the new low and high.
    • For 'l': Set low = ans (since the secret number is larger than your guess) then recalculate the midpoint.
  2. Simplified Win Condition: Just check for 'c'—the user will only input this when you've guessed correctly.
  3. Robust Input Handling: Added .lower() so the program accepts uppercase inputs like 'H' or 'L' too.
  4. Cleaner String Formatting: Used f-strings instead of concatenation for readability.

Testing with 34

Let's walk through your test case (secret number 34):

  1. Initial guess: (0+100)//2 = 50 → user inputs 'h'
  2. New high = 50, guess becomes (0+50)//2 =25 → user inputs 'l'
  3. New low=25, guess becomes (25+50)//2=37 → user inputs 'h'
  4. New high=37, guess becomes (25+37)//2=31 → user inputs 'l'
  5. New low=31, guess becomes (31+37)//2=34 → user inputs 'c'
  6. Game ends correctly!

内容的提问来源于stack exchange,提问作者FanonX Rogers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:40:59