Basic coin flipper program - logical error help

Paul McGuire ptmcg at austin.rr._bogus_.com
Tue Feb 21 23:37:50 EST 2006


<bonono at gmail.com> wrote in message
news:1140578858.586591.243900 at g43g2000cwa.googlegroups.com...
>
> John Zenger wrote:
> > Also, with the functional programming tools of map, filter, and lambda,
> > this code can be reduced to just six lines:
> >
> > import random
> >
> > flips = map(lambda x: random.randrange(2), xrange(100))
> > heads = len(filter(lambda x: x is 0, flips))
> > tails = len(filter(lambda x: x is not 0, flips))
>
> Or a filter/map/lambda free way:
>
> heads = sum(random.randrange(2) for x in xrange(100))
> tails = 100 - heads
>
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






More information about the Python-list mailing list