Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from timeit import timeit
- from random import randint
- list_to_search = [i for i in range(1000000)]
- #######################################################################
- # COPY AND PASTE YOUR linear_search AND binary_search functions below #
- #######################################################################
- def linear_search(search_query, search_list):
- for position, item in enumerate(list_to_search, 1):
- if search_query == item:
- print(item, "is at position", position)
- else:
- False
- def binary_search(list_to_search, value):
- # left to 0
- left = 0
- # right to highest index in list
- right = len(list_to_search) - 1
- # loop that ends when left > right
- while left <= right:
- # mid to int between left and right
- mid = int((right + left)/2)
- # if sorted_list[mid] > value set right to mid
- if list_to_search[mid] > value:
- right = mid - 1
- # if sorted_list[mid] < value set left to mid
- elif list_to_search[mid] < value:
- left = mid + 1
- # if sorted_list[mid] == value return mid
- else:
- return mid
- # loop ends return `False`
- return False
- ls = lambda: linear_search(list_to_search, randint(0,1000000))
- bs = lambda: binary_search(list_to_search, randint(0,1000000))
- #time the functions for 100 runs each
- print("Linear search took:")
- print(timeit(ls, number = 100))
- print("Binary search took:")
- print(timeit(bs, number = 100))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement