5
\$\begingroup\$

I am at the beginning of learning python and one of my homeworks (in chapter regarding loops) where to write a code that would guess user number between 1 - 100.

I believe I used algorithm called binary search.

# Introduction
print('\nThink about a number between 0 - 100 and let me guess which is it.',
      '\n\nI will ask you whether my guess is lower or higher than your number',
      '\nIndicate "l" if lower than your number',
        '"h" if higher than your number and',
        '"e" if my guess is correct.'
      '\n\nYou ready?, let"s start!\n')

# Algorithm
count = 0
lborder = 0
hborder = 100
guess = 50

while True:
    answer = input('Is your number higher, lower or equal to ' + str(guess) + ':')
    if answer == 'l':
        hborder = guess
        guess = round((lborder + guess)/2)
    elif answer == 'h':
        lborder = guess
        guess = round((hborder + guess) / 2)
    elif answer == 'e':
        break
    else:
        print('Unrecognizable answer. Use: "l", "h", "e"')
    count += 1

print('\nHooray! It took me', count, 'to guess your number.', sep=' ')
input('\nPress Enter to Exit.')

My question is basically whether there is a better algorithm for finding those numbers (quicker). Also do you have any other comments about my code.

\$\endgroup\$
  • \$\begingroup\$ The binary search algorithm is optimal for this problem, assuming that users' choices are evenly distributed in the 0..100 range. \$\endgroup\$ – Toby Speight Jun 14 '19 at 10:07
4
\$\begingroup\$

Your calculation of count is incorrect in two ways: 1. You don't count your last guess; 2. You count invalid user input.

I would separate the input validation from the input processing. And I would add some logic to handle user input that leads to trying the same guess repetitively, for this the user has to lie, but who guarantees us they won't?

| improve this answer | |
\$\endgroup\$
-1
\$\begingroup\$

You should use:

guess = int((hborder + guess) / 2)

instead of guess = round((hborder + guess) / 2) for correct computation.

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Could you also explain why this would be the correct way? \$\endgroup\$ – dfhwze Jun 14 '19 at 4:24
  • \$\begingroup\$ That's simply wrong - we want to round up in that case. It's the lborder line that needs to round down. It would be more efficient to simply use integer division, though: (lborder + guess) // 2 and (hborder + guess + 1) // 2. \$\endgroup\$ – Toby Speight Jun 14 '19 at 10:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.