Advertisement
Fareehausman00

Untitled

Sep 21st, 2019
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.56 KB | None | 0 0
  1. #binary search, returns index of closest value
  2.  
  3. sorted_list = [0, 1, 2, 3, 4, 5, 6, 7]
  4.  
  5. def binary_search(lst, x):
  6. left = 0
  7. right = len(lst) -1
  8. best_index = left
  9. while left <= right:
  10. mid = int((left + right) / 2)
  11. if lst[mid] > x:
  12. right = mid - 1
  13. elif lst[mid] < x:
  14. left = mid + 1
  15. else:
  16. best_index = mid
  17. break
  18. if abs(lst[mid] - x) < abs(lst[best_index] - x):
  19. best_index = mid
  20. return best_index
  21.  
  22. print(binary_search(sorted_list, 4.7))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement