Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96166
License: OTHER
1
"""This module contains a code example related to
2
3
Think Python, 2nd Edition
4
by Allen Downey
5
http://thinkpython2.com
6
7
Copyright 2015 Allen Downey
8
9
License: http://creativecommons.org/licenses/by/4.0/
10
"""
11
12
from __future__ import print_function, division
13
14
import random
15
16
17
def has_duplicates(t):
18
"""Returns True if any element appears more than once in a sequence.
19
20
t: list
21
22
returns: bool
23
"""
24
# make a copy of t to avoid modifying the parameter
25
s = t[:]
26
s.sort()
27
28
# check for adjacent elements that are equal
29
for i in range(len(s)-1):
30
if s[i] == s[i+1]:
31
return True
32
return False
33
34
35
def random_bdays(n):
36
"""Returns a list of integers between 1 and 365, with length n.
37
38
n: int
39
40
returns: list of int
41
"""
42
t = []
43
for i in range(n):
44
bday = random.randint(1, 365)
45
t.append(bday)
46
return t
47
48
49
def count_matches(num_students, num_simulations):
50
"""Generates a sample of birthdays and counts duplicates.
51
52
num_students: how many students in the group
53
num_samples: how many groups to simulate
54
55
returns: int
56
"""
57
count = 0
58
for i in range(num_simulations):
59
t = random_bdays(num_students)
60
if has_duplicates(t):
61
count += 1
62
return count
63
64
65
def main():
66
"""Runs the birthday simulation and prints the number of matches."""
67
num_students = 23
68
num_simulations = 1000
69
count = count_matches(num_students, num_simulations)
70
71
print('After %d simulations' % num_simulations)
72
print('with %d students' % num_students)
73
print('there were %d simulations with at least one match' % count)
74
75
76
if __name__ == '__main__':
77
main()
78
79