zharry

Exam Loop Tracing and Flowchart Question

Jun 14th, 2016
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. # What the user can enter
  2. possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  3. # What the actual answer in the program is
  4. ANSWER = "I"
  5.  
  6. # Use https://en.wikipedia.org/wiki/Binary_search_algorithm
  7. # for more details
  8.  
  9. # Set Left Scan location to the first letter
  10. left = 0
  11. # Set Right Scan location to the last letter
  12. right = len(possible) - 1
  13. # Set next guessing location to be the middle value of the left and right scan locations
  14. guessLoc = (left + right) // 2
  15. # Count the number of steps taken
  16. step = 1
  17.  
  18. # Keep trying to get the answer if we still don't have the answer
  19. gotAnswer = False
  20. while not gotAnswer:
  21.     # Find the letter of our current guess
  22.     guess = possible[guessLoc]
  23.     # If the guess is correct, we are done
  24.     if (guess == ANSWER):
  25.         gotAnswer = True
  26.     # If the guess was smaller than the correct answer
  27.     # Set the Left Scan location to the current guess location
  28.     elif (guess < ANSWER):
  29.         left = guessLoc
  30.     # If the guess was greater than the correct answer
  31.     # Set the Right Scan location to the current guess location
  32.     else:
  33.         right = guessLoc
  34.     # Set next guessing location to be the middle value of the left and right scan locations
  35.     guessLoc = (left + right) // 2
  36.     # Print out our current guess and step counter
  37.     print("Guess #{}: {}".format(step, guess))
  38.     step += 1
Add Comment
Please, Sign In to add comment