fork(3) download
  1. # The tuesday boy problem
  2. # http://s...content-available-to-author-only...s.com/evolutionblog/2011/11/08/the-tuesday-birthday-problem/
  3. # http://e...content-available-to-author-only...a.org/wiki/Boy_or_Girl_paradox
  4. # Sounds complicated and counter-intuitive, right?
  5. # Python to the rescue!
  6.  
  7. # I have changed the wording in the problem to be less ambiguous:
  8. # "If you ask someone whom you know has two children, whether they have
  9. # at least one boy born on a tuesday, what is the probability that
  10. # both children are boys?"
  11.  
  12. import itertools
  13. import fractions
  14.  
  15. GENDERS = 'boy girl'.split()
  16. DAYS = 'mon tue wed thu fri sat sun'.split()
  17.  
  18. def has_two_boys((child1, child2)):
  19. #Do you have two boys?
  20. return child1[0] == 'boy' and child2[0] == 'boy'
  21.  
  22. def question(child):
  23. #Is this child a boy born on a tuesday?
  24. return child == ('boy', 'tue')
  25.  
  26. def show_probability(pairs):
  27. nr_boy_pairs = len(filter(has_two_boys, pairs))
  28. print '%d pairs, where %d are boy pairs' % (len(pairs), nr_boy_pairs)
  29. print 'gives', fractions.Fraction(nr_boy_pairs, len(pairs))
  30. print
  31.  
  32. CHILD_TYPES = list(itertools.product(GENDERS, DAYS))
  33. #All these pairs are equally common
  34. #(if we pretend that each day and gender is equally likely for each birth):
  35. ALL_CHILD_PAIRS = list(itertools.product(CHILD_TYPES, CHILD_TYPES))
  36.  
  37. print 'Probability that a person has two boys:'
  38. show_probability(ALL_CHILD_PAIRS)
  39.  
  40. #Now we ask all parents the question
  41. YES_PARENTS = [pair for pair in ALL_CHILD_PAIRS
  42. #Is any of your children a boy born on a tuesday?
  43. if question(pair[0]) or question(pair[1])]
  44.  
  45. print 'Probability that a person has two boys, given that they answer yes:'
  46. show_probability(YES_PARENTS)
  47.  
Success #stdin #stdout 0.08s 12432KB
stdin
Standard input is empty
stdout
Probability that a person has two boys:
196 pairs, where 49 are boy pairs
gives 1/4

Probability that a person has two boys, given that they answer yes:
27 pairs, where 13 are boy pairs
gives 13/27