Guess My Number Game

Andrew Dalke adalke at mindspring.com
Sun May 16 10:57:28 EDT 2004


Andrea Griffini
> Not really python related, but...
>
> >On average, the shortest possible runtime (and also a deterministic
runtime of
> >O(log2(high-low))) will be achieved if you use interval walking.
  ...
> supposing that guess(x) returns -1, 0 or 1 depending
> if the number is too low, correct or too high.

And not really an answer to the OP; here's a solution which uses
the bisect module, letting it do the heavy work.  It uses the same sort
of guess function you have, tied to Python's __cmp__.  It isn't an answer
because it's rather too complicated for someone learning programming.

import bisect

def find(min = 1, max = 100):
    print "Think of a number between", min, "and", max
    a = range(min, max+1)
    try:
        bisect.bisect_left(a, Guess())
        print "Your number isn't between", min, "and", max
        print "Maybe you weren't thinking of an integer?"
    except Done, e:
        print "And it only took", e.count, "guesses"

class Done(Exception):
    def __init__(self, answer, count):
        self.answer = answer
        self.count = count

class Guess:
    def __init__(self):
        self.count = 0
    def __cmp__(self, val):
        self.count = self.count + 1
        answer = raw_input("Is it %d? ([y] for yes, [<] for less than "
                      "and [>] for greater than)? " % val)
        if answer == "y":
            raise Done(answer, self.count)
        if answer == "<":
            return -1
        return 1

>>> from number_guess import find
>>> find(1, 10)
Think of a number between 1 and 10
Is it 6? ([y] for yes, [<] for less than and [>] for greater than)? <
Is it 3? ([y] for yes, [<] for less than and [>] for greater than)? y
And it only took 2 guesses
>>> find(1, 100)
Think of a number between 1 and 100
Is it 51? ([y] for yes, [<] for less than and [>] for greater than)? <
Is it 26? ([y] for yes, [<] for less than and [>] for greater than)? >
Is it 39? ([y] for yes, [<] for less than and [>] for greater than)? <
Is it 33? ([y] for yes, [<] for less than and [>] for greater than)? >
Is it 36? ([y] for yes, [<] for less than and [>] for greater than)? >
Is it 38? ([y] for yes, [<] for less than and [>] for greater than)? y
And it only took 6 guesses
>>> find(1, 10)
Think of a number between 1 and 10
Is it 6? ([y] for yes, [<] for less than and [>] for greater than)? n
Is it 9? ([y] for yes, [<] for less than and [>] for greater than)? <
Is it 8? ([y] for yes, [<] for less than and [>] for greater than)? <
Is it 7? ([y] for yes, [<] for less than and [>] for greater than)? <
Your number isn't between 1 and 10
Maybe you weren't thinking of an integer?
>>>

                    Andrew
                    dalke at dalkescientific.com





More information about the Python-list mailing list