Chapter 16 Solutions

Exercise 1 (Sarah)


In [1]:
class Time(object):
    """Represents the time of day.
    attributes: hour, minute, second
    """
time = Time()
time.hour = 11
time.minute = 59
time.second = 30

def print_time(time):
    thetime= '%.2d:%.2d:%.2d' %(time.hour, time.minute, time.second)
    print thetime
    
print_time(time)


11:59:30

Exercise 3 (Liu)


In [ ]:


In [5]:
import copy

class Time(object):
    """Represents the time of day.
       
    attributes: hour, minute, second
    """

def print_time(t):
    print '(%.2d:%.2d:%.2d)' % (t.hour, t.minute, t.second)

def get_seconds(time):
    return (time.hour * 60 + time.minute) * 60 + time.second
    
def is_after(t1, t2):
    return get_seconds(t1) > get_seconds(t2)

def increment(time, seconds):
    time.second += seconds
    
    # get the right minutes
    min_increment = time.second/60
    time.second = time.second%60
    time.minute += min_increment
    
    # get the right hours
    hour_increment = time.minute/60
    time.minute = time.minute%60
    time.hour += hour_increment
    
time = Time()
time.hour = 11
time.minute = 59
time.second = 30

print_time(time)

copied_time = copy.deepcopy(time)

increment(copied_time, 189)
print_time(time)
print_time(copied_time)
print is_after(copied_time, time)


(11:59:30)
(11:59:30)
(12:02:39)
True

Exercise 6 (Dan)


In [2]:
class Time(object):
    """Represents the time of day.
       
    attributes: hour, minute, second
    """
    
def time_to_int(time):
    minutes = time.hour * 60 + time.minute
    seconds = minutes * 60 + time.second
    return seconds

def int_to_time(seconds):
    time = Time()
    minutes, time.second = divmod(seconds, 60)
    time.hour, time.minute = divmod(minutes, 60)
    return time

def str_time(time):
    return '{0:02d}:{1:02d}:{2:02d}'.format(time.hour, time.minute, time.second)

def mul_time(time, n):
    return int_to_time(int(time_to_int(time) * n))

def average_mile_time(race_time, miles):
    return mul_time(race_time, 1./miles)

r = Time()
r.hour = 2
r.minute = 2
r.second = 57
miles = 26.2188
d = {'miles':miles, 'race_time':str_time(r), 'avg_mile': str_time(average_mile_time(r, miles))}
print('Running a {miles} mile race with a time of {race_time} yields an average mile time of {avg_mile}'.format(**d))


Running a 26.2188 mile race with a time of 02:02:57 yields an average mile time of 00:04:41