Advertisement
Mori007

Compline&binary

May 13th, 2019
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.51 KB | None | 0 0
  1. from timeit import timeit
  2. from random import randint
  3.  
  4. list_to_search = [i for i in range(1000000)]
  5.  
  6. #######################################################################
  7. # COPY AND PASTE YOUR linear_search AND binary_search functions below #
  8. #######################################################################
  9. def linear_search(search_query, search_list):
  10.     for position, item in enumerate(list_to_search, 1):
  11.         if search_query == item:
  12.             print(item, "is at position", position)
  13.         else:
  14.             False
  15.  
  16. def binary_search(list_to_search, value):
  17.     # left to 0
  18.     left = 0
  19.     # right to highest index in list
  20.     right = len(list_to_search) - 1
  21.     # loop that ends when left > right
  22.     while left <= right:
  23.         # mid to int between left and right
  24.         mid = int((right + left)/2)
  25.         # if sorted_list[mid] > value  set right to mid
  26.         if list_to_search[mid] > value:
  27.             right = mid - 1
  28.         # if sorted_list[mid] < value  set left to mid
  29.         elif list_to_search[mid] < value:
  30.             left = mid + 1
  31.         # if sorted_list[mid] == value  return mid
  32.         else:
  33.             return mid
  34.     # loop ends return `False`
  35.     return False
  36.    
  37. ls = lambda: linear_search(list_to_search, randint(0,1000000))
  38. bs = lambda: binary_search(list_to_search, randint(0,1000000))
  39.  
  40. #time the functions for 100 runs each
  41. print("Linear search took:")
  42. print(timeit(ls, number = 100))
  43.  
  44. print("Binary search took:")
  45. print(timeit(bs, number = 100))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement