[Tutor] I flip a coin 1 million times what is the consecutive times it will come up head and come up tails

Steven D'Aprano steve at pearwood.info
Wed Feb 27 09:21:54 EST 2019


On Tue, Feb 26, 2019 at 01:34:33PM -0700, shaeffer at q.com wrote:

> I am learning python.  I wanted to test my ability by making a program to
> keep track of the flip of a coin to find how many consecutive times it came
> up heads and tails.

Here's how to count the number of times it comes up heads (1) or tails 
(0):

from collections import Counter
from random import randint
c = Counter(randint(0, 1) for i in range(1000000))
print(c)

Obviously when you do it you will get different results, but here's 
mine:

Counter({1: 500481, 0: 499519})


If you want to count how many *consecutive* heads or tails happen, we 
can do this:

from itertools import groupby
it = groupby(randint(0, 1) for i in range(1000000))
c = Counter(len(tuple(x[1])) for x in it)
print(c)


When I run it, I get this:

Counter({1: 250180, 2: 124648, 3: 62760, 4: 31075, 5: 15707, 6: 7998, 7: 
3778, 8: 1966, 9: 989, 10: 501, 11: 219, 12: 136, 13: 49, 14: 22, 15: 
11, 16: 6, 18: 4, 17: 1})


which tells me that there are 250180 sequences of one head or one tail; 
124648 sequences of two heads or two tails; 62760 sequences of three 
heads or three tails, and so on to 4 sequences of 18 heads or tails.

If you want to see what is going on a bit better:

it = groupby(randint(0, 1) for i in range(20)) # a bit smaller...
for k, x in it:
    t = tuple(x)
    print("got", len(t), "consecutive", ("heads" if k==1 else "tails"), t)


which when I ran it gave me:

got 1 consecutive heads (1,)
got 1 consecutive tails (0,)
got 4 consecutive heads (1, 1, 1, 1)
got 3 consecutive tails (0, 0, 0)
got 1 consecutive heads (1,)
got 1 consecutive tails (0,)
got 7 consecutive heads (1, 1, 1, 1, 1, 1, 1)
got 1 consecutive tails (0,)
got 1 consecutive heads (1,)




-- 
Steven


More information about the Tutor mailing list