Last active
February 1, 2025 11:28
-
-
Save nitori/f3dfd9bc961625a371ae9907929ddc52 to your computer and use it in GitHub Desktop.
Very simple guessing game, to demonstrate binary search. Select a bound, and choose for yourself a number within that bound.
This file contains hidden or 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
def which() -> str: | |
print(f'1) Correct!\n2) My number is smaller.\n3) My number is bigger') | |
while True: | |
res = input('Type 1, 2 or 3: ') | |
if not res.isdecimal() or int(res) not in (1, 2, 3): | |
print('Invalid input!') | |
continue | |
break | |
return ['correct', 'smaller', 'bigger'][int(res) - 1] | |
def main(): | |
lower_bound = int(input("Enter the lower bound: ")) | |
upper_bound = int(input("Enter the upper bound: ")) + 1 | |
guesses = 0 | |
while lower_bound < upper_bound: | |
mid = (upper_bound + lower_bound) // 2 | |
print(f'Is our number {mid}?\n') | |
guesses += 1 | |
result = which() | |
if result == 'correct': | |
print(f'So your number is {mid}! I got it in {guesses} guess{'es' if guesses != 1 else ''}!') | |
break | |
if result == 'smaller': | |
# users number is smaller | |
upper_bound = mid | |
else: | |
lower_bound = mid | |
print() | |
else: | |
print('Hmm... it seems I missed your number?') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment