Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # binary search
- # needs a sorted list
- sorted_list = [1, 2, 3, 4, 4, 4, 4, 4, 5, 6, 7, 8, 9]
- #[1,2,4,5,8]
- def binary_search(asorted_list, avalue):
- left = 0 # left to 0
- right =len(asorted_list)-1 # right to highest index in list
- while left <= right: # loop that ends when left > right
- mid = int((left + right)/2) # mid to int between left and right
- #print(left, right, mid)
- if asorted_list[mid] > avalue:
- right = mid - 1 # if sorted_list[mid] > value set right to mid - 1
- rightdist=round(abs(asorted_list[right]-avalue),3) # nummerical distance from mid
- #print(left, right, mid)
- elif asorted_list[mid] < avalue:
- left = mid + 1
- leftdist=round(abs(asorted_list[left]-avalue),3) # nummerical distance from mid
- #print(left, right, mid)
- else:
- countmid = (asorted_list.count(asorted_list[mid])) # count number of items
- firstmid =(asorted_list.index(asorted_list[mid])) # index of the first item
- lastmid = firstmid + countmid -1 # index of the last item
- return (f"{avalue} was found at position {mid}, {avalue} appears {countmid} times, first occurence postn {firstmid}, last occurence postn {lastmid} ")
- # location of a found item
- if leftdist > rightdist:
- nearno = asorted_list[right]
- pos = right
- else:
- nearno = asorted_list[left]
- pos = left
- return (f"The search for {avalue} was not found, nearest number is {nearno} at position {pos}")
- print(binary_search(sorted_list,4.5))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement