Number Guessing Game in Python using Binary Search
In the number guessing game, the user selects a number within a defined range and then the program guesses the number. If the number guessed is wrong then the user tells the program that is the actual number is greater than the guessed number or not. Similarly, the program again guesses the number until the actual number is not guessed.
Approach: The idea is to use binary search, where in each step the half portion of the search space is reduced. Below is the illustration of the approach:
- Initialize the start and end range of the number guessing.
- Guess the number as middle of the search space. That is
- If the number guessed is correct, then terminate the program.
- Otherwise, Ask the user that guessed number is less than the guessed number or not. If yes then reduce the search space accordingly.
Below is the implementation of the above approach:
N N Y
Number Guessing game in python Guess a number in range (1 to 10) Is the number is 5 ? N Actual number is greater than 5 ? N Is the number is 2 ? Y Voila ! Successfully Guessed Number.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.