Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96165
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
15
class Time:
16
"""Represents the time of day.
17
18
attributes: hour, minute, second
19
"""
20
21
22
def print_time(t):
23
"""Prints a string representation of the time.
24
25
t: Time object
26
"""
27
print('%.2d:%.2d:%.2d' % (t.hour, t.minute, t.second))
28
29
30
def int_to_time(seconds):
31
"""Makes a new Time object.
32
33
seconds: int seconds since midnight.
34
"""
35
time = Time()
36
minutes, time.second = divmod(seconds, 60)
37
time.hour, time.minute = divmod(minutes, 60)
38
return time
39
40
41
def time_to_int(time):
42
"""Computes the number of seconds since midnight.
43
44
time: Time object.
45
"""
46
minutes = time.hour * 60 + time.minute
47
seconds = minutes * 60 + time.second
48
return seconds
49
50
51
def add_times(t1, t2):
52
"""Adds two time objects.
53
54
t1, t2: Time
55
56
returns: Time
57
"""
58
assert valid_time(t1) and valid_time(t2)
59
seconds = time_to_int(t1) + time_to_int(t2)
60
return int_to_time(seconds)
61
62
63
def valid_time(time):
64
"""Checks whether a Time object satisfies the invariants.
65
66
time: Time
67
68
returns: boolean
69
"""
70
if time.hour < 0 or time.minute < 0 or time.second < 0:
71
return False
72
if time.minute >= 60 or time.second >= 60:
73
return False
74
return True
75
76
77
def main():
78
# if a movie starts at noon...
79
noon_time = Time()
80
noon_time.hour = 12
81
noon_time.minute = 0
82
noon_time.second = 0
83
84
print('Starts at', end=' ')
85
print_time(noon_time)
86
87
# and the run time of the movie is 109 minutes...
88
movie_minutes = 109
89
run_time = int_to_time(movie_minutes * 60)
90
print('Run time', end=' ')
91
print_time(run_time)
92
93
# what time does the movie end?
94
end_time = add_times(noon_time, run_time)
95
print('Ends at', end=' ')
96
print_time(end_time)
97
98
99
if __name__ == '__main__':
100
main()
101
102