Exemplo n.º 1
0
 def test_input_validation(self):
     with self.assertRaises(ValueError):
         binary_search_iterative([], 2)
     with self.assertRaises(ValueError):
         binary_search_iterative([1, 2], None)
     with self.assertRaises(ValueError):
         binary_search_iterative(['a', 'b'], 'b')
     with self.assertRaises(ValueError):
         binary_search_iterative([], None)
     with self.assertRaises(ValueError):
         binary_search_iterative([1, 2, 3, 3, -1, 2], 2)
Exemplo n.º 2
0
def pair_sum_sorting(arr, k):
	'''
	Using sorting - O(n logn)

	'''
	number_of_items = len(arr)
	if number_of_items < 2:
		return 
	arr.sort()
	for index, item in enumerate(arr):
		index_pair = binary_search_iterative(arr, index, number_of_items - 1, k - item)
		if index_pair and index_pair > index:
			print item, arr[index_pair]
Exemplo n.º 3
0
def infinite_search(a, num) -> int:
    low = 0
    i = 1
    if a[low] == num:
        return low
    while True:
        if i > len(a) - 1:
            i = len(a) - 1
        if a[i] == num:
            return i
        if a[i] > num:
            # Some low condition
            j = low + 1
            return j + binary_search_iterative(arr=a[j:i], num=num)
        if a[i] < num:
            low = i
            i = i * 2
Exemplo n.º 4
0
 def test_edge_locations(self):
     self.assertEqual(binary_search_iterative([-12, 3, 5, 8], 8), 3)
     self.assertEqual(binary_search_iterative([-12, 3, 5, 8], -12), 0)
Exemplo n.º 5
0
 def test_target_in_items(self):
     self.assertEqual(binary_search_iterative([-1, 4, 5, 11, 18, 23], 4), 1)
     self.assertEqual(binary_search_iterative([-19, -13, 0, 1, 2], 1), 3)
Exemplo n.º 6
0
 def test_binary_search_iterative_odd_false(self):
     arr = [5, 9, 10, 55, 73]
     val = 89
     answer = binary_search.binary_search_iterative(arr, val)
     self.assertEqual(False, answer)
Exemplo n.º 7
0
 def test_binary_search_iterative_odd_true(self):
     arr = [5, 9, 10, 55, 73]
     val = 5
     answer = binary_search.binary_search_iterative(arr, val)
     self.assertEqual(True, answer)
Exemplo n.º 8
0
import logging
import os, sys

try:
    user_paths = os.environ['PYTHONPATH'].split(os.pathsep)
except KeyError:
    user_paths = []
print(user_paths)
import binary_search

logging.basicConfig(filename='myapp.log', level=logging.INFO)
logging.info('Started')
binary_search.binary_search_iterative(
    input_array=[1, 2, 3, 4, 5, 7, 8, 9, 12, 22, 34, 36], value=20)
logging.info('Finished')
from binary_search import binary_search_iterative

# Test iterative binary_search
test_list = [1, 3, 9, 11, 15, 19, 29]
test_val = 25
print(binary_search_iterative(test_list, test_val))  # -1, that is, not found

test_val = 15
print(binary_search_iterative(test_list,
                              test_val))  # 4, that is, 15 found at index 4