Skip to content

Instantly share code, notes, and snippets.

@leotrs
Created August 13, 2016 16:26
Show Gist options
  • Save leotrs/fa78933b712122925df9eabfc97cf9e9 to your computer and use it in GitHub Desktop.
Save leotrs/fa78933b712122925df9eabfc97cf9e9 to your computer and use it in GitHub Desktop.
# Merged your top-level comment into the docstring.
""" Exercise 8, Chapter 10
This exercise pertains to the so-called Birthday Paradox, which you can read
about at http://en.wikipedia.org/wiki/Birthday_paradox.
If there are 23 students in your class, what are the chances that two of you
have the same birthday? You can estimate this probability by generating random
samples of 23 birthdays and checking for matches. Hint: you can generate random
birthdays with the randint function in the random module.
"""
# Imports are usually placed at the top of the file.
import random
# Added a num_students variable so the code has fewer hardcoded
# constants. Also changed trial to num_trials.
def birthday_paradox(num_trials=1000, num_students=23):
"""
Return the observed frequency of same-day birthdays in a population of
size num_students, sampling num_trials times.
"""
total = 0
# Anonymized the loop counter as you're never using it
for _ in range(num_trials):
# List comprehensions are a readable alternative to list-building
# for loops.
bDayList = sorted(random.randint(0, 365) for _ in range(num_students))
# This is no longer needed, look ahead.
# sameDay = False
for i in range(len(bDayList) - 1):
if bDayList[i] == bDayList[i + 1]:
# You want to count every time you find a sameDay. Before,
# you were incrementing total by one after the loop,
# incrementing it only once even if found many.
total += 1
return total / num_trials
if __name__ == '__main__':
# prop -> prob
prob = birthday_paradox(50)
print("The propability is ", prob, "percent" )
# Strictly speaking, the probability is the ration total / num_trials.
# This ratio times 100 is the percentage. Since the docstring says we're
# returning the probability, this is exactly what we return, and we let the
# caller convert to a percentage if they need it. I relocated the print to
# outside your function. Now, your function only does one thing, which is a
# desirable property of modularized code. Before, your function computed
# the percentage AND printed it to the screen, handling to two different
# responsibilities at the same time.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment