Norman Silverstone wrote:

> > Heh, you will find that Python is practically executable pseudo-code!
> >
> > Untested:
> >
> >
> > def guess_number():
> >     # please don't cheat the poor computer...
> >     print "Guess a number."
> >     lo = 0
> >     hi = 100
> >     while True:
> >         guess = (lo+hi)//2
> >         ans = raw_input("Is it %d? y/n " % guess)
> >         if ans in ('y', 'yes'):
> >             break
> >         ans = raw_input("Too high? y/n ")
> >         if ans in ("y", "yes"):
> >             hi = guess-1
> >         else:
> >             lo = guess+1
> >
> > This should run, and it will *almost* do what you want.
>
> Thanks for that but I think it is too simplistic. It appears OK for the
> first guess, which is 50 but, what about the next guess.

did you test the script?  here's a simulator:

import re

number = 0
guess = None
count = 0

def raw_input(prompt):
    global count, guess
    reply = "n"
    m = re.search("\d+", prompt)
    if m:
        # guess a number
        count = count + 1
        guess = int(m.group())
        if guess == number:
            reply = "y"
    else:
        # check if too high
        if guess > number:
            reply = "y"
    print prompt, reply
    return reply

def guess_number():
    # please don't cheat the poor computer...
    print "Guess a number."
    lo = 0
    hi = 100
    while True:
        guess = (lo+hi)//2
        ans = raw_input("Is it %d? y/n " % guess)
        if ans in ('y', 'yes'):
            break
        ans = raw_input("Too high? y/n ")
        if ans in ("y", "yes"):
            hi = guess-1
        else:
            lo = guess+1

for number in range(0, 100+1):
    print "NUMBER IS", number
    count = 0
    guess_number()
    print "SUCCESS AFTER", count, "GUESSES"

# end

> Comments please.

if this had been a java "let's pretend you're the java runtime" certification
question, you would have failed.

</F>



-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to