[Tutor] Simple guessing game - need help with the math
Dave Angel
davea at davea.name
Wed Aug 13 21:13:19 CEST 2014
Greg Markham <greg.markham at gmail.com> Wrote in message:
Please post as text. Because you used html, I cannot quote your
message, or indeed even see it at all while replying. There are
other problems frequently triggered by html, but on to my
response.
You don't specify the python version you're writing for. I have
to guess 3.x, since your use of input would have been improper in
2.x.
Your immediate problem is indeed caused by truncation. In python
version 2.x, dividing an int ny 2 will truncate down. You can
fix that by using
change = int ((1 + change)/ 2)
You also need to repeat that in the appropriate elif clause.
You do have other problems, however, Your calculation for the
new guess is wrong in the elif clause. See if you can spot the
problem. Your while loop termination condition will end the loop
if a user types something other than one of the three valid ones.
And your logic when the user says 'c' starts the next game
without reinitializing guess to 50.
Your use of round in the guess= lines is superfluous. But you may
need to add 1 here as well. I'd suggest starting change at 100,
and cutting it in half before adding or subtracting it from the
guess.
Incidentally, once your code is fixed, it'll converge much
faster than the other random suggestion. Further, the binary
search technique is well worth understanding and mastering.
If I were coding this, then instead of keeping a 'change'
variable, I'd keep an upperlimit and a lowerlimit one. Start them
at 0 and 101, and start your loop. Each time through the loop
your guess would be halfway between the limits. And each time the
user tells you that you were high or low, you'd adjust the
upperlimit or lowerlimit respectively.
--
DaveA
More information about the Tutor
mailing list