The Two Children Problem
How to solve it using code
class Event:
def __init__(self, pred, condition=None):
self.pred = pred
self.condition = condition
def __or__(self, pred):
return Event(self.pred, pred.pred)
class Probability:
def __init__(self, sample_space):
self.sample_space = sample_space
def __call__(self, event):
if event.condition:
num = len({x for x in self.sample_space if event.pred(x) and event.condition(x)})
den = len({x for x in self.sample_space if event.condition(x)})
return num / den
else:
num = len({x for x in self.sample_space if event.pred(x)})
den = len(self.sample_space)
return num/den
sample_space = {1,2,3,4,5,6}
p = Probability(sample_space)
# define the event of getting an even number
is_even = Event(lambda x : x%2 == 0)
# the probability of getting even number
p(is_even)
greater_3 = Event(lambda x : x>3)
p(is_even | greater_3)
sample_space = {"GG","GB","BG","BB"}
p = Probability(sample_space)
older_is_boy = Event(lambda x: x[0] == "B")
at_least_one_boy = Event(lambda x: "B" in x)
both_boy = Event(lambda x: x.count("B") == 2)
p(both_boy | older_is_boy)
p(both_boy | at_least_one_boy)