def test_linear_vs_binary(self): a = [i for i in range(20)] for i, x in enumerate(a): lin_r = binary_search.linear_search(a, x) assert i == lin_r bin_r = binary_search.binary_search(a, x) assert i == bin_r lin_r = binary_search.linear_search(a, a[-1] + 1) assert -1 == lin_r bin_r = binary_search.binary_search(a, a[-1] + 1) assert -1 == bin_r
def test_binary_search_too_low(self): # arrange arr = self.get_array() key = -3 # act result = binary_search(arr, key) # assert self.assertEqual(-1, result)
def test_binary_search_key_in_array(self): # arrange arr = self.get_array() key = 450 # act result = binary_search(arr, key) # assert self.assertEqual(7, result)
def test_binary_search_key_not_found(self): # arrange arr = self.get_array() key = 2 # act result = binary_search(arr, key) # assert self.assertEqual(-1, result)
def test_binary_search_with_duplicates(self): # arrange arr = self.get_array() arr.insert(2, 78) key = 78 # act result = binary_search(arr, key) # assert self.assertEqual(2, result)
def test_finding_absent_element(self): """ Test that it can find an element absent from a list. """ test_list = [1, 2, 3, 4] self.assertEqual(binary_search(test_list, 6), -1, "Should be -1")
def test_finding_present_element(self): """ Test that it can find an element existing in a list. """ test_list = [1, 2, 3, 4] self.assertEqual(binary_search(test_list, 3), 2, "Should be 2")
def test_answer(): a = [1, 5, 8, 12, 13] assert binary_search(a=a, x=23) == -1 assert binary_search(a=a, x=8) == 2
def test_stress(): random.seed(400) numbers = sorted(random.sample(range(1, pow(10, 9)), 3 * pow(10, 4))) values = sorted(random.sample(range(1, pow(10, 9)), pow(10, 5))) for x in values: binary_search(a=numbers, x=x)
def test_worst_problem_size(self): a = [i for i in range(10 ** 5)] for x in range(len(a), len(a) + 10 ** 5): assert -1 == binary_search.binary_search(a, x)
def test_middle_element_odd(self): a = [i for i in range(10 ** 5 - 1)] assert len(a) // 2 == binary_search.binary_search(a, a[len(a) // 2])
def test_worst_case(self): a = [i for i in range(10 ** 5)] assert len(a) - 1 == binary_search.binary_search(a, a[-1])