Sunday, October 6, 2019

Binary Search 2

BinarySearch2
In [1]:
# Guess the Number Game
# Adapted from: www.101computing.net/guess-the-number-binary-search/  

# Implement this code, and play with it until you understand it completely

lower = 0  
upper = 100  
  
#Retrieve and validate number to guess  
number = int(input("Type a number between 1 and 100? "))
while not (number>=lower and number<=upper):  
    number = int(input("Type a number between 1 and 100? "))  

#Complete the code by implementing a binary search...
midValue = (lower + upper)//2
print("Computer Guess: " + str(midValue))  
#... Check if it's a guess, a lower or a higher value...

# Here is a rough solution
# feel free to clean up this code or implement your own solution
while midValue != number:
    if  number > midValue:
        print("guess too low")
        lower = midValue
    else: 
        print("guess too high")
        upper = midValue
    midValue = (lower + upper)//2
    print("Computer Guess: " + str(midValue))
    
print("success!")    
Type a number between 1 and 100? 8
Computer Guess: 50
guess too high
Computer Guess: 25
guess too high
Computer Guess: 12
guess too high
Computer Guess: 6
guess too low
Computer Guess: 9
guess too high
Computer Guess: 7
guess too low
Computer Guess: 8
success!