def test_find_last_item(self): val = len(self.arr) - 1 result = binary_search(self.arr, val) self.assertEqual(result, val, f'Result {result} is not {val} as expected')
def run(G): def find_max_flow(flow): path = bfs_path(G, s, t, condition=min_weight(flow)) return SelectAndMore((flow, path)) if path != None else Less min, max = min_max(map(weight, G.E)) max_flow, path = binary_search(min, max, find_max_flow) return max_flow
def exponential_search(collection, search_value): """Return element's index if predicate is true. Implementation of an iterative version of the algorithm Args: collection: sorted indexed collection search_value: search element Returns: index (int): index elementa if it exist, else -1 """ length = len(collection) if length == 0: return -1 if collection[0] == search_value: return 0 index = 1 while index < length and collection[index] <= search_value: index *= 2 return binary_search(collection[:index], search_value)
def test_find_first_element(self): val = 0 result = binary_search(self.arr, val) self.assertEqual(result, 0, f'Result {result} is not 0 as expected')
def test_find_non_existent(self): val = random.randint(1, 100) * -1 result = binary_search(self.arr, val) self.assertIsNone(result, f'Result {result} not None as expected')
def test_find_value_in_array(self): val = random.randint(0, len(self.arr) - 1) pos = binary_search(self.arr, val) self.assertEqual(val, pos, f'Result {pos} not equal to expected {val}')
def test_binary_search(input_list, item, result): assert binary_search(input_list, item) == result
def test_binary_search_invalid(input_list, item): assert binary_search(input_list, item) is None
def test_simple(self): assert binary_search([x for x in range(10000)], 26) == 26, "Expected value (26) was not returned"
def test_not_found(self): assert binary_search([1, 2, 3, 4], 5) == -1, "Expected value (-1) was not returned"