It is said this question is an interview question for some Software Engineer job. The question is like this. In Australia, each family prefer the girls rather than boys. Therefore, the government allows each family to keep having a child until they have a girl. So the question is to check the ratio between boy babies and girl babies for a generation.
There are three possible answers. The first one is the ratio is way larger than one indicating there are more boys than girls. The second one is the opposite and the third one is equal to one meaning the number of boys is roughly the same the number of the girls. The explanations sound reasonable for each case. Most families prefer girls, therefore girls should be dominating. The second explanation is that some families can have quite a few boys until they have a girl. The third explanation is that roughly the probability between boy and girl babies is 50-50 because of the X-Y biology gene equally distribution.
Well, let the compute do the simulation and we’ll know the answer. The Python code is straightforward emulating this scenario.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | #!/usr/bin/env python # https://helloacm.com/boy-or-girl-python-validation/ from random import seed, random seed() boy = 0 girl = 0 def isBoy(): return random() <= 0.5 def birth(): global boy, girl; if isBoy(): boy += 1 # keep trying until a girl birth() else: girl += 1 totalboy = 0 totalgirl = 0 for y in xrange(0, 10): # test ten times for x in xrange(0, 100000): # test 100000 families birth() print boy * 1.0 / girl totalboy += boy totalgirl += girl boy = 0 girl = 0 print "avg = %.3f" % (totalboy * 1.0 / totalgirl) |
#!/usr/bin/env python # https://helloacm.com/boy-or-girl-python-validation/ from random import seed, random seed() boy = 0 girl = 0 def isBoy(): return random() <= 0.5 def birth(): global boy, girl; if isBoy(): boy += 1 # keep trying until a girl birth() else: girl += 1 totalboy = 0 totalgirl = 0 for y in xrange(0, 10): # test ten times for x in xrange(0, 100000): # test 100000 families birth() print boy * 1.0 / girl totalboy += boy totalgirl += girl boy = 0 girl = 0 print "avg = %.3f" % (totalboy * 1.0 / totalgirl)
Let’s have a look at the simulation result for the 10 runs, each run computing the ratio for 100000 families.
0.99579 1.00278 0.99191 1.00234 1.00398 0.99335 0.99882 0.99727 1.00597 1.00332 avg = 1.000
Does this result surprise you?
You may also like: 如果大家要是一直生一直生直到生到女儿, 岂不是男女比例失调啊?
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: Dropbox Provides Light-weight FTP space
Next Post: The Distribution of the Probability of Reaching e, the Natural Log