Thursday, June 28, 2012

Guess my number the functional way

Guess my number on python the functional way:
import random
def getnum() : return int(raw_input("your guess? "))
def match(guess, secret) : 
    r =  ( guess < secret and 'too low') or ( guess > secret and 'too high') or (guess == secret and 'You win!!')
    print r
    print
    return r

def loop(x,z):
    print "try #",z,
    return ('You win!!' != match(getnum(),x) and loop(x,z+1) ) or (z)

def guessnumber():
    secret = random.choice(range(101))
    times = loop(secret,1)
    print "Total # of try's = ",times
    print (times < 3 and "no way!!") or (times < 4 and "very good") or (times < 6 and 'slo-po') or (times > 5 and 'looser!!')
    return

No comments:

Post a Comment