"""File: bin_srch0.py Purpose: Implement binary search of a list of positive ints Run: python bin_srch0.py Input: A sorted list of positive ints Values to search for (<= 0 to quit) Output: The location of the value in the list or None if the searched value isn't in the list. Note: This version has a serious bug. """ def bin_srch(l, min, max, val): """See if val belongs to l between subscript min and subscript max""" mid = (min+max)/2 if val == l[mid]: return mid elif val < l[mid]: return bin_srch(l, min, mid-1, val) else: # val > l[mid] return bin_srch(l, mid+1, max, val) #---------------------------------------------------------------------- def read_ints(l): """Read a line of ints into the list l""" s = raw_input("Enter a sorted sequence of positive ints on one line\n") ls = s.split() for i in ls: l.append(int(i)) #---------------------------------------------------------------------- # Main program l = [] read_ints(l) val = int(raw_input("Enter a value to search for (<= 0 to quit)\n")) while val > 0: loc = bin_srch(l, 0, len(l)-1, val) if loc != None: print "Found", val, "in subscript", loc else: print val, "isn't in the list" val = int(raw_input("Enter a value to search for (<= 0 to quit)\n")) print "Bye!"