Skip to content

Instantly share code, notes, and snippets.

@marquesds
Last active May 21, 2020 17:14
Show Gist options
  • Save marquesds/7019c363dfe334c17763b67095dfa97d to your computer and use it in GitHub Desktop.
Save marquesds/7019c363dfe334c17763b67095dfa97d to your computer and use it in GitHub Desktop.
Binary search
import random
limit = 10000 # Max attempt number: 14 (log2 10000)
numbers = list(range(limit))
def find(number):
begin = 0
end = len(numbers) - 1
attempts = 0
while begin <= end:
attempts += 1
middle = (begin + end) // 2
guess = numbers[middle]
if number == guess:
return number, attempts
elif guess < number:
begin = middle + 1
else:
end = middle - 1
return None, attempts
if __name__ == '__main__':
number = random.randint(0, limit)
found_number, attempts = find(number)
print(f'Found number {found_number} with {attempts} attempts.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment