Code Challenge: Girl / Boy Proportion Problem

Code Challenge: Girl / Boy Proportion Problem

This weekend my roommate shared a little puzzle with me, which goes as follows:

In a country in which people only want boys, every family continues to have children until they have a boy. If they have a girl, they have another child. If they have a boy, they stop. What is the proportion of boys to girls in the country?

I think its tempting to initially think that there will be more boys, but after you consider the number of females that could be born waiting for a boy, you might think the opposite.

He was trying to solve it mathematically using the sum of infinite series, but we had a little race to see who could do the Monte-Carlo simulation first. I was really happy with my 6 line solution!

In [52]:
# Simulate a birth.  0 is male, 1 is female
def birth():
    return np.random.binomial(1, .5)
In [53]:
# Input: number of families to simulate
# Output: proportion of males to females born
def new_society(int):
    female = 0
    for i in range(int):
        while (birth()==0): 
            female = female + 1
    return int/(female+int)
In [54]:
# Simulate 100,000 families trying for a boy
new_society(100000)
Out[54]:
0.49985004498650404

For fun, I wrote another function to measure what the largest family would be in this society.

In [55]:
def new_society_v2(int):
    female = 0
    longest_fam = 0
    temp_size = 0
    for i in range(int):
        while (birth()==0): 
            female = female + 1
            temp_size = temp_size + 1
        if(temp_size > longest_fam):
            longest_fam = temp_size
        temp_size = 0
    return int/(female+int), longest_fam
In [57]:
new_society_v2(100000)
Out[57]:
(0.5025226637721362, 19)

19 kids! Thats a lot of females just to get your male heir.

One thought on “Code Challenge: Girl / Boy Proportion Problem

Leave a Reply

Your email address will not be published. Required fields are marked *