Last active
February 10, 2016 22:41
-
-
Save Radcliffe/06542cbf37fbf5971a0f to your computer and use it in GitHub Desktop.
Probability distribution of the longest run of heads or tails in N tosses of a fair coin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Find the probability distribution of the longest run of heads or tails in N tosses of a fair coin. | |
N = 10 # Number of coin tosses | |
from itertools import product, imap, groupby | |
from collections import Counter | |
# Adapted from http://stackoverflow.com/a/22214180/677398 | |
def longest_run(sequence): | |
return max(sum(1 for _ in group) for key, group in groupby(sequence)) | |
coin_tosses = product('HT', repeat=N) | |
distribution = Counter(imap(longest_run, coin_tosses)) | |
print sorted(distribution.items()) | |
# Expected output: | |
# [(1, 2), (2, 176), (3, 370), (4, 254), (5, 126), (6, 56), (7, 24), (8, 10), (9, 4), (10, 2)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment