patternpythonMinor
Bisection search game
Viewed 0 times
gamebisectionsearch
Problem
I'm starting to learn Python and am trying to optimize this bisection search game.
high = 100
low = 0
guess = (high + low)/2
print('Please think of a number between 0 and 100!')
guessing = True
while guessing:
print('Is your secret number ' + str(guess) + '?')
pointer = raw_input("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.")
if pointer == 'h':
high = guess
guess = (low + guess)/2
elif pointer == 'l':
low = guess
guess = (high + guess)/2
elif pointer == 'c':
guessing = False
else:
print('Sorry, I did not understand your input.')
print('Game over. Your secret number was: ' + str(guess))Solution
Some things I think would improve your code, which is quite correct:
Putting it all together:
- Having variables for
highandlow, you shouldn't hard code their values in the openingprint.
- You should use
//to make sure you are getting integer division.
- You can write
guess = (low + high) // 2only once, if you place it as the first line inside thewhileloop.
- When checking for
pointer, you may want to first convert it to lower case, to make sure bothhandHare understood.
- Make your code conform to PEP8 on things like maximum line length.
- Using the
formatmethod ofstrcan make more clear what you are printing.
Putting it all together:
high, low = 100, 0
print('Please think of a number between {0} and {1}!'.format(low, high))
guessing = True
while guessing:
guess = (low + high) // 2
print('Is your secret number {0}?'.format(guess))
pointer = raw_input("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.").lower()
if pointer == 'h' :
high = guess
elif pointer == 'l' :
low = guess
elif pointer == 'c':
guessing = False
else:
print('Sorry, I did not understand your input.')
print('Game over. Your secret number was {0}.'.format(guess))Code Snippets
high, low = 100, 0
print('Please think of a number between {0} and {1}!'.format(low, high))
guessing = True
while guessing:
guess = (low + high) // 2
print('Is your secret number {0}?'.format(guess))
pointer = raw_input("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.").lower()
if pointer == 'h' :
high = guess
elif pointer == 'l' :
low = guess
elif pointer == 'c':
guessing = False
else:
print('Sorry, I did not understand your input.')
print('Game over. Your secret number was {0}.'.format(guess))Context
StackExchange Code Review Q#22984, answer score: 8
Revisions (0)
No revisions yet.