Advertisement
Guest User

Untitled

a guest
Apr 20th, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. def binary_search(lst, num):
  2. """
  3. A Binary Searching Method that can be used under the condition that the list is sorted
  4. :param lst: A sorted list or tuple
  5. :param num: The number we're searching for
  6. :return: Boolean: If we found the number in the list or not
  7. """
  8. # Define all the points I plan on using
  9. start = 0
  10. end = len(lst) - 1
  11. mid = end // 2
  12. # Our Sentinel value for if we found our value
  13. found = False
  14. while start <= end and not found:
  15. # Is the number we're looking for is at our midpoint
  16. if lst[mid] == num:
  17. found = True
  18. # Is the number greater than the point we're looking at
  19. elif num > lst[mid]:
  20. start = mid + 1
  21. mid = (start + end) // 2
  22. # Is the number lesser than the point we're looking at
  23. elif num < lst[mid]:
  24. end = mid - 1
  25. mid = (start + end) // 2
  26. return found
  27.  
  28.  
  29. from random import randint
  30. l = [i for i in range(1000)]
  31. n = randint(0, 1000)
  32.  
  33. print(binary_search(l, n))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement