1. 练习:字数统计
2. 练习:网络延迟
3. 练习:秒数换算
题目:
# Write a procedure, convert_seconds, which takes as input a non-negative
# number of seconds and returns a string of the form
# '<integer> hours, <integer> minutes, <number> seconds' but
# where if <integer> is 1 for the number of hours or minutes,
# then it should be hour/minute. Further, <number> may be an integer
# or decimal, and if it is 1, then it should be followed by second.
# You might need to use int() to turn a decimal into a float depending
# on how you code this. int(3.0) gives 3
#
# Note that English uses the plural when talking about 0 items, so
# it should be "0 minutes".
#
def convert_seconds():
print convert_seconds(3661)
#>>> 1 hour, 1 minute, 1 second
print convert_seconds(7325)
#>>> 2 hours, 2 minutes, 5 seconds
print convert_seconds(7261.7)
#>>> 2 hours, 1 minute, 1.7 seconds
我的答案:
def convert_seconds(seconds):
second = seconds % 60
minute = int(seconds) / 60 % 60
hour = int(seconds) / 60 / 60
if hour == 1:
hour = str(hour) + ' hour'
else:
hour = str(hour) + ' hours'
if minute == 1:
minute = str(minute) + ' minute'
else:
minute = str(minute) + ' minutes'
if second == 1:
second = str(second) + ' second'
else:
second = str(second) + ' seconds'
return hour + ', ' + minute + ', ' + second
(这里的有一点需要注意,跟我的常识有些冲突,那就是,题目的视频提供的测试用例认为, 0 秒应该是 0 seconds
,即应该是复数形式。)
4. 练习:下载时间计算器
题目:
# Write a procedure download_time which takes as inputs a file size, the
# units that file size is given in, bandwidth and the units for
# bandwidth (excluding per second) and returns the time taken to download
# the file.
# Your answer should be a string in the form
# "<number> hours, <number> minutes, <number> seconds"
# Some information you might find useful is the number of bits
# in kilobits (kb), kilobytes (kB), megabits (Mb), megabytes (MB),
# gigabits (Gb), gigabytes (GB) and terabits (Tb), terabytes (TB).
#print 2 ** 10 # one kilobit, kb
#print 2 ** 10 * 8 # one kilobyte, kB
#print 2 ** 20 # one megabit, Mb
#print 2 ** 20 * 8 # one megabyte, MB
#print 2 ** 30 # one gigabit, Gb
#print 2 ** 30 * 8 # one gigabyte, GB
#print 2 ** 40 # one terabit, Tb
#print 2 ** 40 * 8 # one terabyte, TB
# Often bandwidth is given in megabits (Mb) per second whereas file size
# is given in megabytes (MB).
def download_time():
print download_time(1024,'kB', 1, 'MB')
#>>> 0 hours, 0 minutes, 1 second
print download_time(1024,'kB', 1, 'Mb')
#>>> 0 hours, 0 minutes, 8 seconds # 8.0 seconds is also acceptable
print download_time(13,'GB', 5.6, 'MB')
#>>> 0 hours, 39 minutes, 37.1428571429 seconds
print download_time(13,'GB', 5.6, 'Mb')
#>>> 5 hours, 16 minutes, 57.1428571429 seconds
print download_time(10,'MB', 2, 'kB')
#>>> 1 hour, 25 minutes, 20 seconds # 20.0 seconds is also acceptable
print download_time(10,'MB', 2, 'kb')
#>>> 11 hours, 22 minutes, 40 seconds # 40.0 seconds is also acceptable
(这道题不难,我的思路是把文件大小和带宽转换成同样的单位,然后就很方便计算了,但是单位转换时,要考虑很多种不同的情况,会有很多重复的代码,合并有时一个小麻烦,这道题我跳过了。。)