Advertisement
brendan-stanford

binary_search_right+left

Aug 25th, 2019
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. from random import randint
  2.  
  3. #collect user input to determine size of random list
  4. #n = int(input("Size of random number list:"))
  5. #start_list = [randint(0, 100) for i in range(n)]
  6.  
  7. #demo list for item recognition testing
  8. start_list = [1, 2, 3, 4, 4, 4, 4, 4, 5, 6, 7, 8, 9]
  9.  
  10.  
  11. #sort list
  12. sorted_list = sorted(start_list)
  13.  
  14. #binary search cuts dataset in half after each iteration until midpoint is equal to value
  15. #(neither greater or less); otherwise loop terminates, and False should be returned as value not present
  16. def binary_search(dataset, value):
  17. n = len(dataset)
  18. left = 0
  19. right = n-1
  20. while left <= right:
  21. mid = int((left + right) / 2)
  22. if dataset[mid] > value:
  23. right = mid - 1
  24. elif dataset[mid] < value:
  25. left = mid + 1
  26.  
  27. #return the leftmost item if value repeated
  28. #elif dataset[mid] == value and dataset[mid - 1] == value:
  29. #right = mid - 1
  30. #left = mid - 1
  31.  
  32. #return the rightmost item if value repeated
  33. elif dataset[mid] == value and dataset[mid + 1] == value:
  34. left = mid + 1
  35. right = mid + 1
  36.  
  37. else:
  38. return mid + 1
  39. return False
  40.  
  41. #collect user input for value to search for in binary_search function
  42. guess = int(input("Value to search for:"))
  43. search = binary_search(sorted_list, guess)
  44.  
  45. #report on whether value found
  46. if search != False:
  47. print(guess, "isolated at position", search)
  48. else:
  49. print(guess, "not found.")
  50.  
  51. #print original and sorted list for user inspection
  52. print(start_list)
  53. print(sorted_list)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement