Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. import random
  2. import statistics
  3. import time
  4. from typing import List, Optional
  5. import matplotlib
  6. import matplotlib.pyplot as plt
  7.  
  8.  
  9. # [1, 2, 3, 4, 5], 0
  10. # ^
  11. # [4, 5], 3
  12. # ^
  13. # [4] , 3
  14. # ^
  15.  
  16. # 3
  17.  
  18. def blind_binary_search(haystack: List[int], needle: int, offset=0) -> Optional[int]:
  19. if len(haystack) == 0:
  20. return None
  21.  
  22. partition = len(haystack) // 2
  23.  
  24. if haystack[partition] == needle:
  25. return offset + partition
  26.  
  27. if haystack[partition] > needle:
  28. return blind_binary_search(haystack[:partition], needle, offset)
  29.  
  30. return blind_binary_search(haystack[partition + 1:], needle, partition + 1 + offset)
  31.  
  32.  
  33. def main():
  34. print("Correctness testing...")
  35. try:
  36. for length in range(10):
  37. haystack = [i for i in range(length)]
  38.  
  39. assert blind_binary_search(haystack=haystack, needle=length) is None
  40. assert blind_binary_search(haystack=haystack, needle=-1) is None
  41.  
  42. for target in range(length):
  43. assert blind_binary_search(haystack=haystack, needle=target) == target
  44.  
  45. for target in range(10):
  46. assert blind_binary_search(haystack=[], needle=target) is None
  47.  
  48. for _ in range(10_000):
  49. haystack = [random.randint(-100, 100) for __ in range(random.randint(1, 100))]
  50. haystack.sort()
  51. needle = random.randint(-100, 100)
  52. result = blind_binary_search(haystack=haystack, needle=needle)
  53. if result is not None:
  54. assert haystack[result] == needle
  55. else:
  56. assert needle not in haystack
  57. except AssertionError as e:
  58. print("Faaaaaail")
  59. raise e
  60. else:
  61. print("Paaaaasssssss")
  62.  
  63. print("Performance testing...")
  64.  
  65. average_times = []
  66. length = 1
  67. while length < 10_000_000:
  68. run_times = []
  69. for _ in range(10):
  70. haystack = [i for i in range(length)]
  71. needle = random.randint(0, length)
  72. start_time = time.time()
  73. blind_binary_search(haystack=haystack, needle=needle)
  74. end_time = time.time()
  75. run_times.append(end_time - start_time)
  76. average_times.append(statistics.mean(run_times))
  77. length += 500_000
  78.  
  79. plt.scatter(range(len(average_times)), average_times)
  80. plt.show()
  81.  
  82.  
  83. if __name__ == "__main__":
  84. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement