Program that gives a secret number using bisection search

Asked

Viewed 75 times

0

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

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

The computer will guess until it’s right.

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?

2 answers

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))
  • In fact, I went to pass this program on an edx automatic tester and received the error: https://ibb.co/nkGpBn

  • can understand what’s going on?

3


Complementing the response of Pedro von Hertwig, who pointed out the error of his code.

Can you notice that you used in your code four times the function input exactly with the same message? This is an indicative that your code may not be very well structured. When realizing, it is always good to review your logic and identify the points that repeat. 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 on Repl.it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.