SHARE
TWEET

Binary search

a guest Feb 10th, 2012 72 Never
  1. print """This program will try to determine a number you have randomly chosen from 1 to 100 through binary search.
  2. Please use 'y' for Yes, 'h' for Higher and 'l' for Lower."""
  3.  
  4. def query(lb, ub, turns_taken):
  5.         guess = (int) (lb+ub) / 2
  6.         q = raw_input("Is your number %d? " % guess)   
  7.         if q == 'y':
  8.                 use_plural = "" if turns_taken == 1 else "s"
  9.                 print "Yeah, got it in %d turn%s!" % (turns_taken, use_plural)
  10.         elif q == 'h':
  11.                 query(guess, ub, turns_taken + 1)
  12.         elif q == 'l':
  13.                 query(lb, guess, turns_taken + 1)
  14.         else: #Invalid answer
  15.                 raise ValueError("Please enter 'y' for Yes, 'h' for Higher and 'l' for Lower.")
  16.  
  17. query(1, 100, 1)
RAW Paste Data
Top