Skip to content

Instantly share code, notes, and snippets.

@ripiuk
Created August 3, 2018 20:23
Show Gist options
  • Save ripiuk/86f70f6bdf7952b480d3961139204241 to your computer and use it in GitHub Desktop.
Save ripiuk/86f70f6bdf7952b480d3961139204241 to your computer and use it in GitHub Desktop.
Binary search implementation with python
import time
from collections import namedtuple
MASS = range(1000000000)
SEARCHED_ITEM = 256879
def binary_search(my_list: list, searched_item: int) -> int or None:
start = 0
end = len(my_list) - 1
while start <= end:
middle = (start + end) // 2
if searched_item == my_list[middle]:
return middle
elif searched_item > my_list[middle]:
start = middle + 1
else:
end = middle - 1
return None
def binary_search_recursive(my_list: list, searched_item: int, start: int=0, end: int=None) -> int or None:
if end is None:
end = len(my_list) - 1
if start > end:
return None
middle = (start + end) // 2
if searched_item == my_list[middle]:
return middle
elif searched_item > my_list[middle]:
return binary_search_recursive(my_list, searched_item, start=middle + 1, end=end)
return binary_search_recursive(my_list, searched_item, start=start, end=middle - 1)
if __name__ == '__main__':
Output = namedtuple('Output', ['func_name', 'result', 'time'])
title = Output('Function', 'Result', 'Time')
funcs = [binary_search, binary_search_recursive]
all_the_results = [title]
for func in funcs:
search_start = time.clock()
res = func(MASS, searched_item=SEARCHED_ITEM)
search_time = time.clock() - search_start
all_the_results.append(Output(func.__name__, res, search_time))
func_name_column_size = max([len(str(x.func_name)) for x in all_the_results])
res_column_size = max([len(str(x.result)) for x in all_the_results])
time_column_size = max([len(str(x.time)) for x in all_the_results])
for _name, _result, _time in all_the_results:
print(f'{_name:<{func_name_column_size}} | {str(_result):<{res_column_size}} | '
f'{_time:<{time_column_size}}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment