python习题

装饰器的使用

使用一个装饰器,查看任意函数(除递归函数)运行时间(20分)

import time


# --exeTime
def exeTime(func):
    def newFunc(*args, **kwargs):
        t0 = time.time()

        print("@%s, {%s} start" % (time.strftime("%X", time.localtime()), func.__name__))
        back = func(*args, **kwargs)
        print("@%s, {%s} end" % (time.strftime("%X", time.localtime()), func.__name__))
        print("@%.3fs taken for {%s}" % (time.time() - t0, func.__name__))
        return back
    return newFunc


# --end of exeTime

@exeTime
def foo():
    for i in range(10000000):
        pass

if __name__ == "__main__":
    foo()
    
    
    

按时间顺序输出歌词

musicLrc = “””[00:03.50]传奇
[00:19.10]作词:刘兵 作曲:李健
[00:20.60]演唱:王菲
[00:26.60]
04:40.75[00:36.25]只是因为在人群中多看了你一眼
[04:49.00]
02:47.44再也没能忘掉你容颜
02:54.83梦想着偶然能有一天再相见
03:02.32从此我开始孤单思念
03:08.15
03:09.35想你时你在天边
03:16.90想你时你在眼前
03:24.42想你时你在脑海
03:31.85想你时你在心田
03:38.67
04:09.96[01:36.25]宁愿相信我们前世有约
04:16.37[01:42.47]今生的爱情故事 不会再改变
04:24.82[01:51.18]宁愿用这一生等你发现
04:31.38[01:57.43]我一直在你身旁 从未走远
04:39.55[02:07.85]
“””


# 方法一
import time
dict1 = {}
list_key = []

music_list1 = musicLrc.splitlines()
for i in music_list1:
    music_list2 = i.split(']')  # ['[04:40.75', '[02:39.90', '[00:36.25', '只是因为在人群中多看了你一眼']
    for j in range(len(music_list2)-1):
        list2 = music_list2[j][1:].split(':')   # [1:] 是为了去掉[ 获得完整时间
        times = float(list2[0])*60 + float(list2[1])
        dict1[times] = music_list2[-1]

d = sorted(dict1.items(), key = lambda x:x[0]) # 返回一个
# print(d)

start_time = time.clock()

for key in d:
    tmp = round(key[0],2)
    tmp_min = tmp//60
    tmp_sec = (tmp//1)%60
    tmp_ms = (tmp*100//1)%100
    while True:
        end_time = time.clock()
        if round(end_time,2) == tmp:
            print('[%02.0f:%02.0f.%02.0f%s]'%(tmp_min,tmp_sec,tmp_ms,key[1]))
            break
            
            
# 方法二
import time
#通过]来得知总共需要打印多少歌词
counter = musicLrc.count("]")
#分行切割
list1 = musicLrc.splitlines()
# num是计算打了多少行数据了
num = 0
#标记位
time_self_flag = 0
#开始
start_time = time.clock()

while True:
    end_time = time.clock()
    #获取分钟
    end_time_min = end_time//60
    #获取秒钟
    end_time_sec = (end_time//1)%60
    #获取微妙
    end_time_ms = (end_time*100//1)%100
    #将时间按照 [时:分:秒 复制给变量time_self1
    time_self1 = "[%02.0f:%02.0f.%02.0f" % (end_time_min, end_time_sec, end_time_ms)
    #这里进行判断,是为了避免在同一时间对所有歌词判断多遍
    if time_self1 != time_self_flag:
        time_self_flag = time_self1
        # print(time_self1)
        for i in list1:
            list2 = i.split("]")
            for j in list2:
                #时间戳 与 歌词时间进行对比,相同则打印,不同则推出
                if j == time_self1:
                   print(j+"]"+list2[-1])
                   num += 1
                   break
    #打印完所有歌词,则退出while循环
    if num == counter:
        break
    原文作者:rottengeek
    原文地址: https://segmentfault.com/a/1190000014692237
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞