Tom_Jung

Untitled

Feb 11th, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. def binary_search(sorted_list, value):
  2. left = 0
  3. right = len(sorted_list) - 1
  4.  
  5. while left <= right:
  6. mid = int((right + left)/2)
  7. if sorted_list[mid] > value:
  8. right = mid - 1
  9. elif sorted_list[mid] < value:
  10. left = mid + 1
  11. else:
  12. return mid
  13. return False
  14.  
  15. def test_LtRtAll(sorted_list,value,switch):
  16. x = binary_search(sorted_list,value)
  17. if x == False:
  18. print("Your search for " + str(value) + " returned zero results.")
  19. return False
  20. elif x == True:
  21. return True
  22. ###RETURN LEFT- OR RIGHT-MOST INDEX CONTAINING SEARCH VARIABLE
  23. elif switch == "left" or switch == "right":
  24. if switch == "left":
  25. use = -1
  26. elif switch == "right":
  27. use = 1
  28. while sorted_list[x] == sorted_list[x + use]:
  29. x = x + use
  30. return x
  31. ###RETURN ALL INDEXES CONTAINING SEARCH VARIABLE
  32. elif switch == "all":
  33. a = x
  34. xlist = [x]
  35. while sorted_list[x] == sorted_list[x-1]:
  36. xlist.append(x-1)
  37. x -= 1
  38. print("Xlist_left: ", xlist)
  39. x = a
  40. while sorted_list[x] == sorted_list[x+1]:
  41. xlist.append(x+1)
  42. x += 1
  43. print("Xlist_right:", xlist)
  44. xlist = sorted(xlist)
  45. return xlist
  46.  
  47. sorted_list = [1,2,3,4,4,4,4,4,5,6,7,8,9]
  48. print("Value is at position(s): ", test_LtRtAll(sorted_list, 4, "all"))
Advertisement
Add Comment
Please, Sign In to add comment