Advertisement
brendan-stanford

binary_search_nearest

Aug 26th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 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,1,1,2,3,5,6,7,7]
  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 and left < (n-1) and right > 0:
  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. if mid == 0 or mid-1 == 0:
  30. return 0
  31. else:
  32. right = mid - 1
  33. left = mid - 1
  34.  
  35. #return the rightmost item if value repeated
  36. #elif dataset[mid] == value and dataset[mid + 1] == value:
  37. #if mid >= n:
  38. #return mid
  39. #else:
  40. #left = mid + 1
  41. #right = mid + 1
  42.  
  43. else:
  44. return mid
  45.  
  46. #This section is meant to determine whether the value on the left or right side of mid is closer by calculating their absolute difference, then returning the relevant position (mid + or - 1); print statements for debugging
  47. print("Search value not found; returning next closest value!")
  48. r = abs(value - float(dataset[right]))
  49. #print r
  50. l = abs(value - float(dataset[left]))
  51. #print l
  52. #print mid
  53. if mid == 0:
  54. return mid
  55. elif r < l:
  56. return right
  57. else:
  58. return left
  59.  
  60. #return mid
  61.  
  62. #collect user input for value to search for in binary_search function; convert floating point values to integers and store in query for search'
  63. guess = float(input("Value to search for:"))
  64. #query = round(guess)
  65.  
  66. #preview rounding results
  67. #print("Float:", guess)
  68. #print("Rounded:", query)
  69. search = binary_search(sorted_list, guess)
  70.  
  71. #report on whether value found
  72. if search != False:
  73. print(str(guess), "closest to value", sorted_list[search], "at position", search)
  74. else:
  75. print(str(guess), "closest to value", sorted_list[0], "at position", search)
  76.  
  77. #print original and sorted list for user inspection
  78. print("Original list was:", start_list)
  79. print("Sorted list:", sorted_list)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement