Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #binary search, returns index of closest value
- sorted_list = [0, 1, 2, 3, 4, 5, 6, 7]
- def binary_search(lst, x):
- left = 0
- right = len(lst) -1
- best_index = left
- while left <= right:
- mid = int((left + right) / 2)
- if lst[mid] > x:
- right = mid - 1
- elif lst[mid] < x:
- left = mid + 1
- else:
- best_index = mid
- break
- if abs(lst[mid] - x) < abs(lst[best_index] - x):
- best_index = mid
- return best_index
- print(binary_search(sorted_list, 4.7))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement