Newbie: Help Figger Out My Problem

bruno modulix onurb at xiludom.gro
Tue Jun 28 13:42:13 CEST 2005


ChuckDubya at gmail.com wrote:
> ##Coin Flip: randomly flips 100 "coins" and prints results
> ##Original draft: june 27, 2005
> ##Chuck
> 
> import random
> heads = 0
> tails = 0
> flips = 0
> while flips < 99:
>         coin = random.randrange(0, 2)
>         if coin == 0:
>             heads = heads + 1
heads += 1
>         else:
>             tails = tails + 1
idem
>         flips = flips + 1
idem
> if flips >= 99:
Why do you think you need this test ?-)

>         print "Heads: " + heads
print "Heads: %d" % heads
>         print "Tails: " + tails
idem
>         print "Total: " + flips + "flips"
idem
> raw_input("Press the enter key to exit.")

May I suggest this version ?


from random import randrange

def flip_coins(flips):
    coins = [0, 0]
    for i in xrange(flips):
        coins[randrange(0, 2)] += 1
    return coins[0], coins[1]

if __name__ == "__main__":
    flips = 100
    heads, tails = flip_coins(flips)
    print "Heads: %d\nTails %d\nTotal: %d flips\n" % (heads, tails, flips)
    #raw_input("Press the enter key to exit.")


HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list