Favorite Child

Python Puzzles

Back to the Python! homepage

You live in a society where female children are preferred over male children. By law, couples have to conceive children until they produce a female offspring. If their first child is male, they are allowed to have additional children until a female is born. Once a female is born, they are allowed no additional children.

What is the average ratio of females to males in this society?

The ratio will be 50/50.

import random
female = 0
male = 0
# run the simulation 100,000 million times
for _ in range(100_000):
    # randomly generate a gender (0 for female, 1 for male)
    gender = random.randint(0,1);
    if gender == 0: 
        female += 1  
    # keep generating males until a female is generated
    while gender != 0:    
        male += 1      
        gender = random.randint(0,1)
        if gender == 0: 
            female += 1
# print the results
print('Number of females is ' + str(female))
print('Number of males is ' + str(male))
print('Percentage female is ' + str(female/(female+male)))
print('Percentage male is ' + str(male/(female+male)))