Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 4.8 (102) python bisection search code by Raspary pi (Furure Learn) modified by Ken Adams
- #Uses the function 'binary_search' binary method to search a list for a given value.
- #If the value is not there it can return False or return the nearest item on the list
- # Unfortunately with the code at present (x integer) x.5 would get round down to x instead of up to x+1
- # Another function 'run_binary_search_smallest' will return the lowest index available for an item on the list.
- #my_list=[1, 2, 3, 4, 4, 4, 4, 4, 5, 6, 7, 8, 9]
- my_list = [1,2,3,5,6,7]
- my_value = 3
- def binary_search(sorted_list, value,near):# near is set to 1 if you cant get exact but will accept the nearest
- # left to 0
- left = 0
- # right to highest index in list
- right = len(sorted_list) - 1
- # loop that ends when left > right
- while left <= right:
- # mid to int between left and right
- mid = int((right + left)/2)
- # if sorted_list[mid] > value set right to mid
- if sorted_list[mid] > value:
- right = mid - 1
- # if sorted_list[mid] < value set left to mid
- elif sorted_list[mid] < value:
- left = mid + 1
- # if sorted_list[mid] == value return mid
- else:
- return mid
- # loop ends return `False`
- ###############################looking for the nearst
- if near == 1:
- print("finding the closest")
- if mid == 0: # have searched to the botom of the list so value must be below the bottom
- return 0
- elif mid == len(sorted_list)-1: # have searched to top of list go value beyoud that
- return mid
- else:
- closest = mid-1 #any of the three mid-1, mid, mid+1 could fetch the closest
- # we start at closest = mid-1 and use a for loop to change that if nessary
- for i in range(2):
- if abs(sorted_list[closest]-value) > abs(sorted_list[closest+1]-value):
- closest = closest +1
- return closest
- return False # f near was not set to one the if above is not used so we return False as usual
- # function to find lowest
- def run_binary_search_smallest(my_list, my_number): #uses their binary_search not my own
- first = binary_search(my_list, my_value,)# get one place to start
- while my_list[first] == my_number and first >= 0:
- store_first = first #store the result of the last loop throught the while
- first -= 1 # decrement first
- return store_first
- # CHOOSE WHAT FUNCTION TO RUN
- position = binary_search(my_list, my_value,1)
- #position = run_binary_search_smallest(my_list, my_value)
- print(position)
- print("Looking for " + str(my_value) + " The item at position " + str(position) + " is " +str(my_list[position]))
- print("bye")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement