code for number guessing by computer

Tim Chase python.list at tim.thechases.com
Sun Sep 30 20:22:10 CEST 2007


> hi, please help me,,,,,, a newbie.......send me code for a programme
> in which the computer tell u the number that u guessed............

I can think of at least two versions of this:

>>> _ = raw_input("Think of an integer greater than 1 and less
than 3")
>>> print "Your number was 2!  This code is teh awesome!"

or, if you need to guess an arbitrary number greater than "N",
you can use this spiffy code:

>>> print "Think of an integer greater than zero and I will guess it"
>>> i = 1
>>> while raw_input("Was your number %i?" % i) <> "yes": i += 1
...

>>> print "I guessed your number correctly!"


Oh...unless this was a homework problem and you were looking for
a standard binary search of a problem-space, in which case,
mailing lists don't generally do your homework for you.
However, the first solution I provided is *far* better than a
boring old binary-search because it solves the problem in O(1)
rather than O(log N)  which any good math wonk will tell you is a
much more efficient algorithm!  :)

-tkc








More information about the Python-list mailing list