Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # What the user can enter
- possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- # What the actual answer in the program is
- ANSWER = "I"
- # Use https://en.wikipedia.org/wiki/Binary_search_algorithm
- # for more details
- # Set Left Scan location to the first letter
- left = 0
- # Set Right Scan location to the last letter
- right = len(possible) - 1
- # Set next guessing location to be the middle value of the left and right scan locations
- guessLoc = (left + right) // 2
- # Count the number of steps taken
- step = 1
- # Keep trying to get the answer if we still don't have the answer
- gotAnswer = False
- while not gotAnswer:
- # Find the letter of our current guess
- guess = possible[guessLoc]
- # If the guess is correct, we are done
- if (guess == ANSWER):
- gotAnswer = True
- # If the guess was smaller than the correct answer
- # Set the Left Scan location to the current guess location
- elif (guess < ANSWER):
- left = guessLoc
- # If the guess was greater than the correct answer
- # Set the Right Scan location to the current guess location
- else:
- right = guessLoc
- # Set next guessing location to be the middle value of the left and right scan locations
- guessLoc = (left + right) // 2
- # Print out our current guess and step counter
- print("Guess #{}: {}".format(step, guess))
- step += 1
Add Comment
Please, Sign In to add comment