Skip to content

Instantly share code, notes, and snippets.

@kamalbanga
Last active March 1, 2020 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamalbanga/d7cd971e65a85ff2a961d69122fcf972 to your computer and use it in GitHub Desktop.
Save kamalbanga/d7cd971e65a85ff2a961d69122fcf972 to your computer and use it in GitHub Desktop.
Monte Carlo simulations of some problems; to estimate probabilities
from random import choices, sample
from statistics import mean
def common_birthday(k):
'''Generate k independent uniformly random birthdays & check if there are any repeats'''
birthdays = choices(range(1, 366), k=k)
return len(set(birthdays)) != k
>>> mean(common_birthday(23) for _ in range(10000))
0.4979
def matching(k=52):
'''Simulates an experiment to permute 'k' cards and check if any jth card's label is j'''
idx_labels = enumerate(sample(range(k), k))
return any(idx == label for idx, label in idx_labels)
>>> mean(matching() for _ in range(10000))
0.6421
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment