📚 The CoCalc Library - books, templates and other resources
License: OTHER
"""This module contains a code example related to12Think Python, 2nd Edition3by Allen Downey4http://thinkpython2.com56Copyright 2015 Allen Downey78License: http://creativecommons.org/licenses/by/4.0/9"""1011from __future__ import print_function, division1213import random141516def has_duplicates(t):17"""Returns True if any element appears more than once in a sequence.1819t: list2021returns: bool22"""23# make a copy of t to avoid modifying the parameter24s = t[:]25s.sort()2627# check for adjacent elements that are equal28for i in range(len(s)-1):29if s[i] == s[i+1]:30return True31return False323334def random_bdays(n):35"""Returns a list of integers between 1 and 365, with length n.3637n: int3839returns: list of int40"""41t = []42for i in range(n):43bday = random.randint(1, 365)44t.append(bday)45return t464748def count_matches(num_students, num_simulations):49"""Generates a sample of birthdays and counts duplicates.5051num_students: how many students in the group52num_samples: how many groups to simulate5354returns: int55"""56count = 057for i in range(num_simulations):58t = random_bdays(num_students)59if has_duplicates(t):60count += 161return count626364def main():65"""Runs the birthday simulation and prints the number of matches."""66num_students = 2367num_simulations = 100068count = count_matches(num_students, num_simulations)6970print('After %d simulations' % num_simulations)71print('with %d students' % num_students)72print('there were %d simulations with at least one match' % count)737475if __name__ == '__main__':76main()777879