Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def binary_search(sorted_list, value):
- left = 0
- right = len(sorted_list) - 1
- while left <= right:
- mid = int((right + left)/2)
- if sorted_list[mid] > value:
- right = mid - 1
- elif sorted_list[mid] < value:
- left = mid + 1
- else:
- return mid
- return False
- def test_LtRtAll(sorted_list,value,switch):
- x = binary_search(sorted_list,value)
- if x == False:
- print("Your search for " + str(value) + " returned zero results.")
- return False
- elif x == True:
- return True
- ###RETURN LEFT- OR RIGHT-MOST INDEX CONTAINING SEARCH VARIABLE
- elif switch == "left" or switch == "right":
- if switch == "left":
- use = -1
- elif switch == "right":
- use = 1
- while sorted_list[x] == sorted_list[x + use]:
- x = x + use
- return x
- ###RETURN ALL INDEXES CONTAINING SEARCH VARIABLE
- elif switch == "all":
- a = x
- xlist = [x]
- while sorted_list[x] == sorted_list[x-1]:
- xlist.append(x-1)
- x -= 1
- print("Xlist_left: ", xlist)
- x = a
- while sorted_list[x] == sorted_list[x+1]:
- xlist.append(x+1)
- x += 1
- print("Xlist_right:", xlist)
- xlist = sorted(xlist)
- return xlist
- sorted_list = [1,2,3,4,4,4,4,4,5,6,7,8,9]
- print("Value is at position(s): ", test_LtRtAll(sorted_list, 4, "all"))
Advertisement
Add Comment
Please, Sign In to add comment