Skip to content

Instantly share code, notes, and snippets.

@Radcliffe
Last active February 10, 2016 22:41
Show Gist options
  • Save Radcliffe/06542cbf37fbf5971a0f to your computer and use it in GitHub Desktop.
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
# 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