Program that warns a secret number using bisection search

1

Create a program that guesses a secret number using bisection search!

The user thinks of an integer between 0 (inclusive) and 100 (not inclusive). The computer, using bisection search, gives a hint and the user responds with h (high), l (low) or c (right)

The computer will hunch until it hits.

My code:

print("Please think of a number between 0 and 100!")
print("#Enter 'h' to indicate the guess is too high.\
      Enter 'l' to indicate the guess is too low.\
      Enter 'c' to indicate I guessed correctly.") 

#Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low.
#Enter 'c' to indicate I guessed correctly. 

inicio =0
fim =100
meio = round((inicio +fim)/2)
guess = input("Is your secret number {}?:".format(meio))

while guess != "c":

    if guess == "h":
        fim =meio
        meio = round((inicio + fim)/2)
        guess = input("Is your secret number {}?:".format(meio))
    elif guess == "l":
        inio =meio
        meio = round((inio  +fim)/2)
        guess = input("Is your secret number {}?:".format(meio))
    else:
        print("Sorry, I did not understand your input.")
        guess = input("Is your secret number {}?:".format(meio))
print("Game over. Your secret number was:{}".format(meio))

What's wrong with the code?

    
asked by anonymous 17.04.2018 / 17:19

2 answers

3

Complementing the answer from the Peter von Hertwig , which pointed out the error of your code.

Can you see that you have used the input function in your code four times exactly with the same message? This is indicative that your code may not be very well structured. When you realize it, it is always good to review your logic and identify the points that are repeated. For example, you can rewrite your code as follows:

print('''Please think of a number between 0 and 100!

Enter 'h' to indicate the guess is too high.
Enter 'l' to indicate the guess is too low.
Enter 'c' to indicate I guessed correctly.
''')

start = 0
stop = 100

while True:
    guess = (start + stop) // 2
    response = input(f'Is your secret number {guess}? ')
    if response == 'c':
        break
    elif response == 'h':
        stop = guess
    else:
        start = guess

print(f'Game over. Your secret number was: {guess}')

See working at Repl.it

    
17.04.2018 / 18:11
4

A typo made you create a new variable.

elif guess == "l":
    inio =meio
    meio = round((inio  +fim)/2)
    guess = input("Is your secret number {}?:".format(meio))

should be:

elif guess == "l":
    inicio = meio
    meio = round((inicio  +fim)/2)
    guess = input("Is your secret number {}?:".format(meio))
    
17.04.2018 / 17:49