def search(A, target): if len(A) == 0: return -1 s = 1 while s < len(A): if A[s] != A[0]: break s += 1 e = len(A) while e > s: if A[e-1] != A[0]: break e -= 1 r = binary_search(A, lambda x: -1 if x<A[0] else 1, search_range(s,e)) if target >= A[0]: r = binary_search(A, target, search_range(s-1, r[0])) elif target < A[0]: r = binary_search(A, target, search_range(r[0], e)) if search_range_size(r) <= 0: return -1 return r[0]
def my_search(arr, item): """ Searches a number in an array that has the form described in problem 3. :param arr: list of numbers as described in problem 3. :param item: number to be searched. """ l = 0 r = len(arr) - 1 while r - l > 2: #print(l) #print(r) m = int(np.floor((l + r) / 2)) if arr[m] > arr[r]: if arr[l] <= item and item <= arr[m - 1]: return l + binary_search(arr[l:m], item) else: l = m else: if arr[m + 1] <= item and item <= arr[r]: return m + 1 + binary_search(arr[m + 1:r + 1], item) else: r = m for k in range(l, r + 1): if arr[k] == item: return k print('{} is not in input array.'.format(item)) return None
def test_binary_search(self): values=[5,2,4,9,0,6,1] #To check whether assertion is true or false self.assertEqual(binary_search(values,9),9) self.assertEqual(binary_search(values,1),1) self.assertEqual(binary_search(values,7),-1)
def test_binary_search_raises_an_error_with_an_invalid_target(self): target = 1 try: binary_search(self.sorted_values, target) except ValueError as e: self.assertEqual(e.message, "{} was not found in the list".format(target))
def search(A, target): if len(A) == 0: return -1 s = 1 while s < len(A): if A[s] != A[0]: break s += 1 e = len(A) while e > s: if A[e - 1] != A[0]: break e -= 1 r = binary_search(A, lambda x: -1 if x < A[0] else 1, search_range(s, e)) if target >= A[0]: r = binary_search(A, target, search_range(s - 1, r[0])) elif target < A[0]: r = binary_search(A, target, search_range(r[0], e)) if search_range_size(r) <= 0: return -1 return r[0]
def test_binary_search(self): index = binary_search([1, 3, 7, 9, 12], 1) self.assertEqual(index, 0) index = binary_search([1, 3, 7, 9, 12], -1) self.assertEqual(index, None) index = binary_search([1, 3, 7, 9, 12], 12) self.assertEqual(index, 4)
def test_binary_search(self): arr1 = [-9, -8, -6, -4, -3, -2, 0, 1, 2, 3, 5, 7, 8, 9] arr2 = [] self.assertEqual(binary_search(arr1, -8), 1) self.assertEqual(binary_search(arr1, 0), 6) self.assertEqual(binary_search(arr2, 6), -1) self.assertEqual(binary_search(arr2, 0), -1)
def test_binary_search(self): arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] arr2 = [1, 3, 5, 7, 9, 11, 13, 15, 17] arr3 = [2, 4, 6, 8, 10, 12, 14, 16, 18] self.assertEqual(binary_search(arr1, 5), 4) self.assertEqual(binary_search(arr2, 10), False) self.assertEqual(binary_search(arr3, 16), 7)
def test_binary_search(self): self.assertEqual( binary_search([9.36908730, 1.18286813, 388.56234885, 702.52504444]), 48.33345944061875) self.assertEqual( binary_search( [0.12470827, 0.66066792, 1429.23301339, -665.29260768]), 30.320073943585157)
def test_binary_search(): d = [1, 2, 5, 6, 7, 9, 10, 13, 16, 17, 21, 24, 27, 33] low = 0 high = len(d) - 1 assert binary_search(d, 2, low, high) == 1 assert binary_search(d, 24, low, high) == 11 assert binary_search(d, 3, low, high) == -1 assert binary_search(d, 0, low, high) == -1 assert binary_search(d, 34, low, high) == -1
def test_binary_search(self): self.assertEqual(binary_search.binary_search([1, 2, 3], 1), 0) self.assertEqual(binary_search.binary_search([1, 2, 3], 2), 1) self.assertEqual(binary_search.binary_search([1, 2, 3], 3), 0) self.assertEqual(binary_search.binary_search([1, 2, 3, 4], 1), 0) self.assertEqual(binary_search.binary_search([1, 2, 3, 4], 2), 1) self.assertEqual(binary_search.binary_search([1, 2, 3, 4], 3), 2) self.assertEqual(binary_search.binary_search([1, 2, 3, 4], 4), 0) self.assertEqual(binary_search.binary_search([1, 2], 1), 0) self.assertEqual(binary_search.binary_search([1, 2], 2), 1) self.assertEqual(binary_search.binary_search([1], 1), 0)
def test_binary_search(self): array = [1, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 6] self.assertEqual(10, binary_search(array, 5)) self.assertEqual(11, binary_search(array, 6)) self.assertEqual(None, binary_search(array, 7)) self.assertEqual(None, binary_search(array, -1)) # Test binary_search_recur self.assertEqual(10, binary_search_recur(array, 0, 11, 5)) self.assertEqual(11, binary_search_recur(array, 0, 11, 6)) self.assertEqual(-1, binary_search_recur(array, 0, 11, 7)) self.assertEqual(-1, binary_search_recur(array, 0, 11, -1))
def test_method1(self): arr = range(0, 10) self.assertEqual(binary_search(arr, 1), 1) for i in arr: self.assertEqual(binary_search(arr, i), i) self.assertEqual(binary_search(arr, -1), -1) self.assertEqual(binary_search(arr, 100), -1)
def test_whenNumberDoesNotExist_shouldReturnFalse(self): # with haystack = [i for i in range(200)] # when out_of_range1 = binary_search(haystack, -1) out_of_range2 = binary_search(haystack, 200) # then assert not out_of_range1 assert not out_of_range2
def count_searches(value, ordered_array, total_time): start = time() cont = 0 while True: cont += 1 binary_search(value, ordered_array) sequential_search(value, ordered_array) end = time() total = end - start if total_time <= total: break return cont
def test_binary_search(self): result = binary_search(list, 1) self.assertEqual(result, 1) result = binary_search(list, 6) self.assertEqual(result, 6) result = binary_search(list, 11) self.assertEqual(result, None) result = binary_search(list, 0) self.assertEqual(result, 0)
def test_regular(self): arr = [] self.assertEqual(binary_search(arr, 10), -1) arr = [0] self.assertEqual(binary_search(arr, 0), 0) self.assertEqual(binary_search(arr, 1), -1) arr = [i for i in range(10)] for i in arr: self.assertEqual(binary_search(arr, i), i) self.assertEqual(binary_search(arr, 100), -1)
def main(): primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 ] result = binary_search(5, primes) print(result) result = binary_search(79, primes) print(result) result = binary_search_recursion(5, primes, 0, len(primes)) print(result) result = binary_search_recursion(79, primes, 0, len(primes)) print(result)
def test_whenStringExists_shouldReturnTrue(self): # with haystack = ("just", "another", "string", "tuple") # when first = binary_search(haystack, "just") random = binary_search(haystack, "another") last = binary_search(haystack, "tuple") # then assert first assert random assert last
def test(self): self.assertTrue(binary_search([1, 2, 3, 4, 5], 4)) self.assertFalse(binary_search([1, 2, 3, 4, 5], 0)) self.assertTrue(binary_search([1, 2, 6, 9, 43], 2)) self.assertTrue(binary_search([1, 2, 6, 6, 9, 43], 6)) self.assertFalse(binary_search([1, 2, 3, 4, 5], 6)) self.assertTrue(binary_search([-2, -1, 3, 4, 5], 5)) self.assertTrue(binary_search([-56, -43, -20, -6, -2], -43)) self.assertFalse(binary_search([-56, -43, -20, -6, -2], -42)) self.assertFalse(binary_search([1, 2, 3, 4, 5], 1.5))
def remove_redirection_part(geonames): for g in geonames: not_redirection = binary_search(redirections0, g.wikipedia_url) if not_redirection is -1: wiki_key = g.wikipedia_url.replace("http://en.wikipedia.org/wiki/", "").replace("_", " ") final_url = binary_search(redirections, wiki_key, cross_columns=True, col_sep="\t", finding_column=0, return_column=1) if final_url is not -1: g.wikipedia_url = final_url else: wiki_key = wiki_key.lower() final_url = binary_search(redirections, wiki_key, cross_columns=True, col_sep="\t", finding_column=0, return_column=1) if final_url is not -1: g.wikipedia_url = final_url return geonames
def test_search(): testlist = [ 0, 1, 2, 8, 13, 17, 19, 32, 42, ] assert binary_search(testlist, 3) is None assert binary_search(testlist, 13) == 4
def test_n_elements(self): in_array = [1, 2, 5, 6, 8, 9, 13, 17, 29] # Value not in set # Below range self.assertIsNone(binary_search(in_array, -4)) # In range self.assertIsNone(binary_search(in_array, 14)) # Above range self.assertIsNone(binary_search(in_array, 51)) # Value in set for i, elem in enumerate(in_array): self.assertEqual(binary_search(in_array, elem), i)
def test_whenNumberExists_shouldReturnTrue(self): # with haystack = [i for i in range(200)] # when first = binary_search(haystack, 0) random_value1 = binary_search(haystack, 22) random_value2 = binary_search(haystack, 190) last = binary_search(haystack, 199) # then assert first assert random_value1 assert random_value2 assert last
def check_value(self, input_list, value): found_index = binary_search(input_list, value) # print('found index is: ', found_index, 'value is: ', value) if ((found_index == -1) and (value in input_list)) or ((found_index != -1) and (value != input_list[found_index])): exit()
def test_all_nums_in_list(self): input_list = [1, 4, 6, 7, 9, 11, 13] index = 0 for num in input_list: found_index = binary_search(input_list, num) self.assertEqual(index, found_index) index += 1
def first_and_last_index(source: list, target: int): """ Returns the first and last index of the target in source array. Args: source (list): array of elements target (int): target element Returns: list: [first index, last index] """ index = binary_search(source, target) if index == -1: return [-1, -1] first_index = index while source[first_index] == target: if first_index == 0: break if source[first_index - 1] == target: first_index -= 1 else: break last_index = index while source[last_index] == target: if last_index == len(source) - 1: break if source[last_index + 1] == target: last_index += 1 else: break return [first_index, last_index]
def optimal_strategies(silent_duel_input: SilentDuelInput) -> SilentDuelOutput: '''Compute an optimal pair of corresponding strategies for the silent duel problem.''' # First compute a's and b's, and check to see if a_1 == b_1, in which case quit. intermediate_state = compute_as_and_bs(silent_duel_input, alpha=0, beta=0) a1 = intermediate_state.player_1_transition_times[0] b1 = intermediate_state.player_2_transition_times[0] if abs(a1 - b1) < SEARCH_EPSILON: return compute_player_strategies( silent_duel_input, intermediate_state, alpha=0, beta=0, ) # Otherwise, binary search for an alpha/beta searching_for_beta = b1 < a1 print('Binary searching for ' + ('beta' if searching_for_beta else 'alpha')) if searching_for_beta: def test(beta_value): new_state = compute_as_and_bs(silent_duel_input, alpha=0, beta=beta_value) new_a1 = new_state.player_1_transition_times[0] new_b1 = new_state.player_2_transition_times[0] found = abs(new_a1 - new_b1) < SEARCH_EPSILON return BinarySearchHint(found=found, tooLow=new_b1 < new_a1) else: def test(alpha_value): new_state = compute_as_and_bs(silent_duel_input, alpha=alpha_value, beta=0) new_a1 = new_state.player_1_transition_times[0] new_b1 = new_state.player_2_transition_times[0] found = abs(new_a1 - new_b1) < SEARCH_EPSILON return BinarySearchHint(found=found, tooLow=new_a1 < new_b1) search_result = binary_search(test, param_min=0, param_max=1, callback=print) assert search_result.found # the optimal (alpha, beta) pair have product zero. final_alpha = 0 if searching_for_beta else search_result.value final_beta = search_result.value if searching_for_beta else 0 intermediate_state = compute_as_and_bs(silent_duel_input, alpha=final_alpha, beta=final_beta) print(intermediate_state.player_1_transition_times) print(intermediate_state.player_2_transition_times) player_strategies = compute_player_strategies(silent_duel_input, intermediate_state, final_alpha, final_beta) return player_strategies
def test_1(self): """Test not found""" arr = [0, 1, 2, 3, 4, 5] item = 6 self.assertEqual(None, binary_search(arr, item))
def test_binary_search(): test_array = [1, 2, 3, 4, 5, 6, 7] test_value = 4 will_it_blend = search.binary_search(test_array, test_value) print(will_it_blend) assert type(will_it_blend) is int assert will_it_blend == 3
def test_large(self): for (keys, query, answer) in [ (list(range(10 ** 4)), 10 ** 4, -1), (list(range(10 ** 4)), 10 ** 4, -1), (list(range(10 ** 4)), 239, 239), ]: self.assertEqual(binary_search(keys, query), answer)
def testDuplicateElements(self): ''' Точно не знаю, должна ли функция возвращать результат 0 или 1. В данный ситуации вернет 1, но можно дописать в коде условие, чтобы проверяло, не является ли элемент слева таким же и тд. И тогда вернуть крайний левый похожий элемент. ''' self.assertEqual(binary_search([1, 1, 2, 2, 3, 3, 4], 1), 1, 'Problem with duplicate elements')
def test_1(self): array = [1, 5, 8, 12, 13] numbers = [8, 1, 23, 1, 11] result = [] for n in numbers: result.append(binary_search(array, n)) self.assertEqual(result, [3, 1, -1, 1, -1])
def test_small(self): for (keys, query) in [ ([1, 2, 3], 1), ([4, 5, 6], 7), ([1, 2, 3, 4, 5], 6), ]: self.assertEqual(linear_search(keys, query), binary_search(keys, query)) for count in range(1, 1000): keys = sorted([ random.randint(1, 10000) for i in range(random.randint(1, 1000)) ]) query = random.randint(1, 10000) self.assertEqual(linear_search(keys, query), binary_search(keys, query))
def test(): import time, random from binary_search import binary_search seq = [] for i in range(1000): seq.append(i) a = random.randint(1, 1000) c = time.time() sequential_search(seq, a) print("seq, %s", time.time() - c) c = time.time() binary_search(seq, a) print("seq, %s", time.time() - c)
def test_binary_search(self): self.assertEqual(binary_search([1, 3, 4, 6, 8, 9, 11], 4), 2) self.assertEqual(binary_search([1, 3, 4, 6, 8, 9, 11], 6), 3) self.assertEqual(binary_search([1, 3, 4, 6, 8, 9, 11], 8), 4) self.assertEqual(binary_search([1, 3, 4, 6, 8, 9, 11], 1), 0) self.assertEqual(binary_search([1, 3, 4, 6, 8, 9, 11], 11), 6) self.assertIsNone(binary_search([], 100)) self.assertIsNone(binary_search([1, 5, 10], 100)) self.assertIsNone(binary_search([1, 5, 10], -1))
def sum_search(items, value): merge_sort.merge_sort(items, 0, len(items) - 1) for i in xrange(0, len(items)): last_item = items[-i-1] index = binary_search.binary_search(items, value - last_item, 0, len(items) - i - 1) if None != index: return (items[index], last_item) return None
def sort(a, p, q): for i in range(p+1, q+1): k = binary_search.binary_search(a, a[i], p, i-1) if k < i: t = a[i] a[k+1:i+1] = a[k:i] a[k] = t return a
def test_false_case(self): ''' test that the function returns false if the number is not in the desired array ''' a = [1,2,3,4,5,6,7] focus = 13 self.assertFalse(binary_search(a, focus))
def searchRange(A, target): r = binary_search(A, target) if search_range_size(r) <= 0: return [-1, -1] a, b = r return [a, b-1]
def test_case_of_multiple_values(self): ''' test that the binary search returns the correct inedex of an integer in a sorted list with repeated values ''' a = [11, 12, 12, 12, 13, 14, 15, 16, 17, 17, 18, 29, 30] focus = 13 expected_index = 4 self.assertEqual(binary_search(a, focus), expected_index)
def test_simple_case(self): ''' test that the binary search returns the correct index of an integer in a sorted list ''' a = [1,2,3,4,5,6,7,8,9] focus = 3 expected_index = 2 self.assertEqual(binary_search(a, focus), expected_index)
def run_binary_sort(): primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] did_pass = True for val in primes: result = binary_search(val, primes) if not isinstance(result, int) or result > 5: did_pass = False assert_true(did_pass, True, 'Binary Search')
def sum_exist(a,x): merge_sort(a,0,len(a)-1) ##print a for i in range(len(a)): #binary_search(list,begin,end,key) if binary_search(a,i,len(a)-1,x-a[i]): return True return False
def find_element_in_matrix(element, matrix): matrix_length = len(matrix) middle_index = matrix_length / 2 median = matrix[middle_index] if element >= median[0] and element <= median[-1]: return binary_search(element, median) elif matrix_length <= 1: return None elif element > median[-1]: return find_element_in_matrix(element, matrix[middle_index + 1:]) elif element < median[0]: return find_element_in_matrix(element, matrix[:middle_index])
def two_sum_to_search(lst, val): """ :description: finds all pairs of values that add to the value using binary search on the difference between the value and each item :time: O(nlogn) - sorting in nlogn, finding in O(logn) :space: O(1) :execution: running run 10000 times in 16.1 seconds """ found = False lst = sorted(lst) for i, x in enumerate(lst): j = binary_search.binary_search(lst, val - x) if j != -1: print 'pair: {} {}'.format(i,j) found = True return found
def findMin(num): s = 1 while s < len(num): if num[s] != num[0]: break s += 1 e = len(num) while e > s: if num[e-1] != num[0]: break e -= 1 r = binary_search(num, lambda x: -1 if x<num[0] else 1, search_range(s,e)) if search_range_size(r) <= 0: if r[0] == e: return num[0] return num[r[0]] return num[r[0]]
def two_sum_array(input_table, low_target, high_target): positive_index = 0 sorted_array = sorted(list(input_table)) counter = 0 loop = 0 for target in range(low_target, high_target+1): loop+=1 print(loop) index = binary_search(sorted_array, target) if index == 0: index = len(sorted_array)-1 while index > -1: number = sorted_array[index] complement = target - number if complement in input_table and complement != number: counter += 1 break index -=1 print(time.clock()) return counter
def test_first(): '''Test a value at the beginning of the list.''' assert binary_search(1, VALUES) == 0
def test_missing_end(): '''Test searching for a missing value at the end.''' assert binary_search(11, VALUES) == -1
def test_missing_middle(): '''Test searching for a missing value in the middle.''' assert binary_search(2, VALUES) == -1
def test_missing_start(): '''Test searching for a missing value at the start.''' assert binary_search(-3, VALUES) == -1
def test_last(): '''Test searching for the last value.''' assert binary_search(10, VALUES) == 7
def test_middle(): '''Test searching for the middle value.''' assert binary_search(5, VALUES) == 4
def test_duplicate(): '''Test a duplicate value.''' assert binary_search(4, VALUES) == 2
def __init__(self, trace_manager): self.logger = logging.getLogger("ramp.TraceWorker") self.trace_manager = trace_manager self.binary_search = binary_search.binary_search()
def test_missing_end(self): """Test searching for a missing value at the end.""" expected = -1 actual = binary_search(VALUES, 11) self.assertEqual(expected, actual, "Error searching for {0}".format(expected))
def test_missing_middle(self): """Test searching for a missing value in the middle.""" expected = -1 actual = binary_search(VALUES, 2) self.assertEqual(expected, actual, "Error searching for {0}".format(expected))