Skip to content

Instantly share code, notes, and snippets.

@anisbhsl
Last active February 2, 2023 05:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anisbhsl/d8f6bcbbebc9c3c867837ba87c79fd7c to your computer and use it in GitHub Desktop.
Save anisbhsl/d8f6bcbbebc9c3c867837ba87c79fd7c to your computer and use it in GitHub Desktop.
Guess The Number : Binary Search Problem
"""
Q1: Two friends, Elaine and Tom, are playing a guessing game with each other.
Elaine thinks of an integer in her mind and Tom needs to guess the number.
Tom can ask a question as follows: Is your number greater than or equal to 5
(or any other specified integer)?
Then Elaine has to reply yes or no based on the comparison results of the two numbers.
Design an algorithm, in pseudo-code to help Tom find that number quick.
UAH CS 617 - Spring 2023
"""
"""
Strategy:
1) First find lower and upper bounds to construct the search space
2) Use binary search algorithm to find/guess the number in that bound
"""
def ask_elaine(N):
if N<=-55: #if target number is gt or eq, then return True
return True
else:
return False
def find_bounds(lower, upper):
while 1:
if ask_elaine(lower) and not(ask_elaine(upper)):
return lower, upper
else:
if ask_elaine(lower) and ask_elaine(upper):
lower=lower*10
upper=upper*10
elif not(ask_elaine(lower)) and not(ask_elaine(upper)):
lower=lower-lower*10
upper=upper-upper*10
def guess_the_number():
lower, upper = find_bounds(-55,55)
while lower <= upper:
mid = int((lower+upper)/2)
if ask_elaine(mid):
lower=mid
else:
upper=mid
if abs(upper-lower)==1:
return lower
print(f"lower is {lower} upper is: {upper} \n")
print(guess_the_number())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment