def get_running_time_binary(keys): """Returns the running time for the binary search function. Uses target of -1. Args: keys (list): list of positive, consecutive integers (i.e. not containing -1) Returns: (float): time in seconds required for the function to execute once on the list keys. """ target = -1 start = time.time() sf.binary_search(keys, target, 0, len(keys) - 1) end = time.time() return end - start
def plot_times(min_length, max_length, step): """Produces a plot comparing the worst case running times for binary search and linear search on lists with length between min_length and max_length. Returns: None """ # As the book does it, function is forced to round to zero, because the # float returned by time.time() only has 6 or so decimal places. # Calling each more than once produces a better looking graph. # Binary search is so fast that the book's suggested method of speed-testing # doesn't even work on a reasonably fast desktop... max_list = list(range(max_length)) len_keys = [] seconds_linear = [] seconds_binary = [] for i in range(min_length, max_length + 1, step): keys = max_list[:i] start = time.time() for i in range(10): sf.linear_search(keys, -1) end = time.time() seconds_linear.append(end - start) ## print(f"Linear:\n\tstart was {start}\n\tend was {end}") start = time.time() for i in range(10): sf.binary_search(keys, -1, 0, len(keys)) end = time.time() seconds_binary.append(end - start) # pyplot calls pyplot.plot(range(min_length, max_length + 1, step), seconds_linear, label='Linear search') pyplot.plot(range(min_length, max_length + 1, step), seconds_binary, label='Binary search') pyplot.legend(loc='upper center') pyplot.xlabel('len(keys)') pyplot.ylabel('Time in seconds') pyplot.show()
def query_quakes(ids, data): prompt = 'Earthquake ID (q to quit): ' key = input(prompt) while key.lower() != 'q': index = sf.binary_search(ids, key, 0, len(ids) - 1) ## index = sf.linear_search(ids, key) # for comparison. Will exceed default cpython max recursion depth for worst case i.e. not-found. if index >=0: print('Location: ' + str(data[index][:2]) + '\n' + 'Magnitude: ' + str(data[index][3]) + '\n' + 'Depth : ' + str(data[index][2]) + '\n') else: print('An earthquake with that ID was not found.') key = input(prompt)
def test_not_found_binary_search(self): """Test that target is NOT found by binary search.""" pos = binary_search(self.my_list, -1) self.assertTrue(pos == None)
def test_found_binary_search(self): """Test that target is found by binary search.""" pos = binary_search(self.my_list, 3) self.assertEqual(pos, 1)