Guest User

morebrothers.py

a guest
May 23rd, 2016
578
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. import random
  2.  
  3. class Child:
  4. def __init__(self, family):
  5. self.family = family
  6. @property
  7. def brothers(self):
  8. brothers = 0
  9. for kid in self.family.kids:
  10. if type(kid) == Boy and kid != self:
  11. brothers += 1
  12. return brothers
  13.  
  14. class Girl(Child):
  15. pass
  16.  
  17. class Boy(Child):
  18. pass
  19.  
  20. class Family:
  21. def __init__(self):
  22. self.kids = []
  23. self.haveKids()
  24. def haveKid(self):
  25. gender = random.choice(('Girl', 'Boy'))
  26. if gender == 'Girl':
  27. self.kids.append(Girl(self))
  28. else:
  29. self.kids.append(Boy(self))
  30.  
  31. def haveKids(self):
  32. haveAKid = random.choice((True, False))
  33. while haveAKid:
  34. self.haveKid()
  35. haveAKid = random.choice((True, False))
  36.  
  37. families = []
  38. for i in range(1000000):
  39. families.append(Family())
  40. girls = 0
  41. boys = 0
  42. girlbrothers = 0
  43. boybrothers = 0
  44. for family in families:
  45. for kid in family.kids:
  46. if type(kid) == Girl:
  47. girlbrothers += kid.brothers
  48. girls += 1
  49. else:
  50. boybrothers += kid.brothers
  51. boys += 1
  52.  
  53. print('Out of a sample of', girls, 'girls, and', boys, 'boys:')
  54. print('The average girl has', girlbrothers/girls, 'brothers.')
  55. print('The average boy has', boybrothers/boys, 'brothers.')
  56. print('Ratio:', (girlbrothers/girls)/(boybrothers/boys))
Advertisement
Add Comment
Please, Sign In to add comment