grokking-algorithms/chapter1/binary.py

44 lines
823 B
Python
Raw Permalink Normal View History

2024-01-04 17:41:01 +00:00
import logging
import random
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
def binary_search(arr, item):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
guess = arr[mid]
if guess == item:
return mid
elif guess > item:
high = mid - 1
else:
low = mid + 1
return None
2024-01-08 10:38:49 +00:00
LOWER = 1000
UPPER = 1000000
SAMPLE_SIZE = 1000
2024-01-04 17:41:01 +00:00
numbers = random.sample(range(LOWER, UPPER), SAMPLE_SIZE)
numbers.sort()
2024-02-06 21:53:17 +00:00
seen = set()
count = 0
2024-01-08 10:38:49 +00:00
result = None
2024-02-06 21:53:17 +00:00
while not result:
2024-01-04 17:41:01 +00:00
guess = random.randrange(LOWER, UPPER)
2024-02-06 21:53:17 +00:00
if guess not in seen:
count += 1
seen.add(guess)
result = binary_search(numbers, guess)
2024-01-04 17:41:01 +00:00
2024-02-06 21:53:17 +00:00
print(f"Found {guess} at index {result} after {count} attempts")