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 sethigh = 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 thanans). - When the guess is too low (
'l'),low = ans*2jumps the range back up, completely abandoning the narrow search you started. - The win condition
check_ans == 'c' and check_ans == user_numis also flawed:check_ansis a string, anduser_numis 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
- Proper Range Updates:
- For
'h': Sethigh = ans(since the secret number is smaller than your guess) then recalculateansas the midpoint of the newlowandhigh. - For
'l': Setlow = ans(since the secret number is larger than your guess) then recalculate the midpoint.
- For
- Simplified Win Condition: Just check for
'c'—the user will only input this when you've guessed correctly. - Robust Input Handling: Added
.lower()so the program accepts uppercase inputs like'H'or'L'too. - Cleaner String Formatting: Used f-strings instead of concatenation for readability.
Testing with 34
Let's walk through your test case (secret number 34):
- Initial guess:
(0+100)//2 = 50→ user inputs'h' - New
high = 50, guess becomes(0+50)//2 =25→ user inputs'l' - New
low=25, guess becomes(25+50)//2=37→ user inputs'h' - New
high=37, guess becomes(25+37)//2=31→ user inputs'l' - New
low=31, guess becomes(31+37)//2=34→ user inputs'c' - Game ends correctly!
内容的提问来源于stack exchange,提问作者FanonX Rogers
相关产品推荐
相关产品推荐

