A robust Python implementation of the classic "Guess the Number" game featuring two distinct algorithms. This project demonstrates control flow, random number generation, and search space optimization logic.
- Two Game Modes:
- User Guess: The player attempts to find a random number generated by the system.
- Computer Guess: The computer attempts to solve for the user's secret number using an adaptive algorithm.
- Search Space Optimization: The
computer_guessfunction dynamically adjusts its upper and lower bounds (highandlow) based on feedback, mimicking a binary search strategy to narrow down the correct answer efficiently. - Edge Case Handling: Includes logic to prevent
random.randinterrors when the lower and upper bounds converge (low == high).
The program generates a random integer between 1 and x. The user receives feedback ("Too High" or "Too Low") until the correct number is identified.
The computer guesses a number, and the user provides feedback:
- H: The guess is too High (Computer adjusts
high = guess - 1) - L: The guess is too Low (Computer adjusts
low = guess + 1) - C: Correct
This feedback loop allows the computer to intelligently eliminate impossible numbers, converging on the solution much faster than random guessing.
-
Clone the repository
git clone [https://github.com/Digao075/guess-number-python.git](https://github.com/Digao075/guess-number-python.git) cd guess-number-python -
Run the script
python main.py
-
To change the range: Modify the function call at the bottom of the script:
computer_guess(100) # Changes range to 1-100
The following snippet demonstrates how the computer refines its search range. This logic prevents the computer from wasting guesses on numbers that have already been ruled out.