Problem

  • Mr. Jones has two children. The older child is a girl. What is the probability that both children are girls?
  • Mr. Smith has two children. At least one of them is a boy. What is the probability that both children are boys?

Using Python to Represent Probability

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

Examples

Before solving the two children problem, let's see of our code can solve the dice problem that we encounter in every introuction to probability course.

Example 1

Rolling a fair dice with 6 faces, what is the probability of getting a even number ?

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)
0.5

Example 2

(We can also look at conditional probability) What is the probability of getting an even number given the result is greater than 3

greater_3 = Event(lambda x : x>3)
p(is_even | greater_3)
0.6666666666666666

Solving the real problem

Let's denote the gender by either the letter 'G'(girl) or 'B'(boy), and hence 'GB' means the elder child is a girl and the younger is a boy.

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)
0.5
p(both_boy | at_least_one_boy)
0.3333333333333333