[Tutor] (no subject)

Alan Gauld alan.gauld at btinternet.com
Thu May 8 15:46:10 CEST 2014


On 08/05/14 11:00, Kevin Johnson wrote:
> user picks a number between 1 and 100 and the computer has to guess,

Hmm, usually its the other way around, the computer picks a number and 
the user guesses it. Interesting twist!

> The highlighted bit is where I think I'm going wrong but I just can't
> think how to make the computer remember the previously closest highest
> and lowest guesses,

I'm not sure why you think you need to do that?

But simply you create a new variable called last_guess
or somesuch and store computer_guess there before you
change it.

But the biggest problem is that the computer is using random values 
between 1 and the current guess(+/-1). That's a very inefficient
way to get to the place you want.

A more efficient technique is something called a binary chop:

You know the users number is between 1 and 100 so you start
in the middle at 50.

If its too high then the users guess is between 1 and 49
so you pick the new middle - say 25

If its too high the target is between 1 and 24m, so you pick
the middle -> 12

and so on.

Similarly if the first guess is too low you know the user is
between 51 and 100 so you pick the middle - 75

If its too high you pick midway between 75 and 100 and so on.

That should pretty much always get the computer to the
right answer within its 10 guesses.

The only values you need to keep track of are the lower
and upper bounds - starting at 1 & 100 respectively.

> user_number = int(input("Pick a number between 1 and 100: "))
> computer_guess = random.randint(1, 100)
> guesses = 1
>
> while computer_guess != user_number:
...

>   if computer_guess > user_number:
>          computer_guess = random.randrange(1, (computer_guess-1))
>      else:
>          computer_guess = random.randint((computer_guess + 1), 100)
>      guesses += 1
>      if computer_guess == user_number:
>          print("Well done you guessed the number was", user_number)
>          print("It took you", guesses, "tries")

There is also a bug in the above code: in the case that the
computer guesses the correct number the else clause causes the
computer to generate a new guess.

So the computer can never win on the first guess!!

The else line should really be:

elif computer_guess < user_number:

Also why use randint() on one line but randrange() on the other?
They are subtly different and only one is correct in this situation.
I'll let you figure out which! :-)

And if you use binary chop you won't need either!


HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list