Pastebin launched a little side project called HostCabi.net, check it out ;-)Don't like ads? PRO users don't see any ads ;-)
Guest

Binary search

By: a guest on Feb 10th, 2012  |  syntax: Python  |  size: 0.64 KB  |  hits: 65  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  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)