Think Python Exercise 16.1

编写一个叫做 print_time 的函数,接收一个 Time 对象并用 时:分:秒 的格式打印它。提示: 格式化序列 %.2d 可以至少两位数的形式打印一个整数,如果不足则在前面补 0。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Time:
    """用于记录时间
    属性:hour, minute, second
    """
    
def print_time(ti):
    print("%.2d:%.2d:%.2d" % (ti.hour,ti.minute,ti.second)) #记得加括号

time1 = Time()
time1.hour = 11
time1.minute = 59
time1.second = 30

print_time(time1)

编写一个叫做 is_after 的布尔函数,接收两个 Time 对象,t1 和 t2 ,若 t1 的时间在 t2 之后,则返回 True ,否则返回 False。挑战:不要使用 if 语句。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Time:
    """用于记录时间
    属性:hour, minute, second
    """
    
def print_time(ti):
    print("%.2d:%.2d:%.2d" % (ti.hour,ti.minute,ti.second)) #记得加括号

def is_after(t1,t2):
    return (t1.hour, t1.minute, t1.second) > (t2.hour, t2.minute, t2.second)

time1 = Time()
time1.hour = 11
time1.minute = 59
time1.second = 30

time2 = Time()
time2.hour = 11
time2.minute = 58
time2.second = 30

is_after(time1,time2)

我们做个练习,编写一个纯函数版本的 increment ,创建并返回一个 Time 对象,而不是修改参数。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Time:
    """用于记录时间
    属性:hour, minute, second
    """
    
def print_time(ti):
    print("%.2d:%.2d:%.2d" % (ti.hour,ti.minute,ti.second)) #记得加括号
    
def increment(t1, seconds):
    """给一个Time对象增加指定的秒数"""
    addedtime = Time()
    minutes, addedtime.second = divmod(t1.hour * 60 * 60 + t1.minute * 60 + t1.second + seconds, 60)
    addedtime.hour, addedtime.minute = divmod(minutes, 60)
    
    return addedtime

time1 = Time()
time1.hour = 11
time1.minute = 59
time1.second = 30

print_time(increment(time1, 90))

我们再做个练习, 使用 time_to_intint_to_time 重写 increment 函数。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Time:
    """用于记录时间
    属性:hour, minute, second
    """

def print_time(ti):
    print("%.2d:%.2d:%.2d" % (ti.hour,ti.minute,ti.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 add_time(t1, t2):
    seconds = time_to_int(t1) + time_to_int(t1)
    return int_to_time(seconds)

def increment(t1,seconds):
    """给一个Time对象增加指定的秒数"""
    return int_to_time(time_to_int(t1) + seconds)

def add_time(t1, t2):
    assert valid_time(t1) and valid_time(t2)
    seconds = time_to_int(t1) + time_to_int(t2)
    return int_to_time(seconds)

time1 = Time()
time1.hour = 11
time1.minute = 59
time1.second = 30

print_time(increment(time1, 90))