Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96141
License: OTHER
1
"""This file contains code used in "Think Stats",
2
by Allen B. Downey, available from greenteapress.com
3
4
Copyright 2010 Allen B. Downey
5
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
6
"""
7
8
import csv
9
import datetime
10
import sys
11
12
import Cdf
13
import myplot
14
15
def ReadBirthdays(filename='birthdays.csv'):
16
"""Reads a CSV file of birthdays and returns a list of date objects.
17
18
The first column of the file must contain dates in MM-DD format.
19
20
Args:
21
filename: string filename
22
23
Returns:
24
list of datetime.date objects"""
25
fp = open(filename)
26
reader = csv.reader(fp)
27
bdays = []
28
29
for t in reader:
30
bday = t[0]
31
month, day = [int(x) for x in bday.split('-')]
32
date = datetime.date(2010, month, day)
33
bdays.append(date)
34
35
return bdays
36
37
def Diff(t):
38
"""Computes the differences between the adjacent elements of a sequence.
39
40
Args:
41
t: sequence of anything subtractable
42
43
Returns:
44
list of whatever is in t
45
"""
46
diffs = []
47
for i in range(len(t)-1):
48
diff = t[i+1] - t[i]
49
diffs.append(diff)
50
return diffs
51
52
53
def Main(script):
54
55
# read 'em and sort 'em
56
birthdays = ReadBirthdays()
57
birthdays.sort()
58
59
# compute the intervals in days
60
deltas = Diff(birthdays)
61
days = [inter.days for inter in deltas]
62
63
# make and plot the CCDF on a log scale.
64
cdf = Cdf.MakeCdfFromList(days, name='intervals')
65
scale = myplot.Cdf(cdf, transform='exponential')
66
myplot.Save(root='intervals',
67
xlabel='days',
68
ylabel='ccdf',
69
**scale)
70
71
if __name__ == '__main__':
72
Main(*sys.argv)
73
74