Last active
May 21, 2020 17:14
-
-
Save marquesds/7019c363dfe334c17763b67095dfa97d to your computer and use it in GitHub Desktop.
Binary search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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