Advertisement
brendan-stanford

binary_search_closest

Aug 26th, 2019
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 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,5,6,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:
  30. #return mid
  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)
  47. print("Search value not found; returning next closest value!")
  48. r = abs(dataset[mid] - dataset[right])
  49. print right
  50. l = abs(dataset[mid] - dataset[left])
  51. print left
  52. if r > l:
  53. return left
  54. else:
  55. return right
  56.  
  57. #return mid
  58.  
  59. #collect user input for value to search for in binary_search function; convert floating point values to integers and store in query for search'
  60. guess = float(input("Value to search for:"))
  61. query = round(guess)
  62.  
  63. #preview rounding results
  64. print(guess)
  65. print(query)
  66. search = binary_search(sorted_list, query)
  67.  
  68. #report on whether value found
  69. if search != False:
  70. print(str(guess), "closest to value", sorted_list[search], "at position", search)
  71. else:
  72. print(str(guess), "closest to value", sorted_list[0], "at position", search)
  73.  
  74. #print original and sorted list for user inspection
  75. print(start_list)
  76. print(sorted_list)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement