Basic coin flipper program - logical error help

Paul McGuire ptmcg at austin.rr._bogus_.com
Wed Feb 22 11:14:31 EST 2006


"Paul McGuire" <ptmcg at austin.rr._bogus_.com> wrote in message
news:yURKf.22750$UN2.3873 at tornado.texas.rr.com...
> <bonono at gmail.com> wrote in message
> news:1140578858.586591.243900 at g43g2000cwa.googlegroups.com...

> sort, then groupby.
>
>
> import itertools
> import random
> h,t = [len(list(g)) for k,g in
itertools.groupby(sorted([random.randrange(2)
> for i in xrange(100)]))]
> print h,t
>
>
By the way, sort + groupby generalizes beyond just coin-flipping.  Here is a
modified version that simulates die rolls.

-- Paul

import itertools
import random

NUM_ROLLS = 1000
dieRolls = [random.randrange(6)+random.randrange(6)+2 for i in
xrange(NUM_ROLLS)]

# create dummy list entries for impossible rolls of 0 and 1
rolls = [None,None]

rolls += [len(list(g)) for k,g in itertools.groupby(sorted(dieRolls))]

# print out nice histogram
for i,r in enumerate(rolls):
    if i > 1:
        print "%2d - %s" % (i,"*"*int(round(r/10.0)))


prints:

 2 - ***
 3 - *****
 4 - *********
 5 - **********
 6 - ***************
 7 - ******************
 8 - **************
 9 - *********
10 - *******
11 - *******
12 - ***






More information about the Python-list mailing list