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!
# Simulate a birth. 0 is male, 1 is female def birth(): return np.random.binomial(1, .5)
# 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)
# Simulate 100,000 families trying for a boy new_society(100000)
For fun, I wrote another function to measure what the largest family would be in this society.
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
19 kids! Thats a lot of females just to get your male heir.