""" search.py Look for a number in a list. """ def search(x, items): """ Return position where x is in items. If not found return -1 """ for i in range(len(items)): #print(i, items[i]) if x == items[i]: return i # Didn't find it. return -1 print("Searching for 4 in [100, 10, 4, 3, 15]") answer = search(4, [100, 10, 4, 3, 15]) print("answer is ", answer) print("Searching for 17 in [100, 10, 4, 3, 15]") answer = search(17, [100, 10, 4, 3, 15]) print("answer is ", answer) def binary_search(x, low_index, high_index, items): """ search assuming items are in order """ # using this binary half each time print(f" binary search: x={x}, low={low_index}, hi={high_index}, items={items}") if low_index > high_index: return -1 else: middle_index = (low_index + high_index) // 2 item = items[middle_index] if x == item: return middle_index elif x < item: return binary_search(x, low_index, middle_index - 1, items) elif x > item: return binary_search(x, middle_index + 1, high_index, items) def search2(x, items): """ start binary search """ return binary_search(x, 0, len(items) - 1, items) print("Searching binary for 4 in [1, 2, 4, 20, 60, 100]") answer = search2(4, [1, 2, 4, 20, 60, 100]) print("answer is ", answer) print("Searching binary for 17 in [1, 2, 4, 20, 60, 100]") answer = search2(17, [1, 2, 4, 20, 60, 100]) print("answer is ", answer)