二、练习

练习1

题目:编写函数,函数执行的时间是随机的

图示:

Python基础第七天

代码:

import time
import random

def func():
    s = 1
    l = []
    for i in range(1,random.randrange(1,50)):
        s *= i               # s的最大值为:s = 1 * 2 * 3...50
        time.sleep(0.05)
        l.append(i)          # 再把变量i添加至列表l里,此时l列表中的元素最大值为l = [1,2,3,4..50]
    print("%s‘sproduct is%d"%(l,s))
func()

 

 

练习2

题目:编写装饰器,为函数加上统计时间的功能

代码:

import time
import random

def timmer(data):
    def wrapper(*args,**kwargs):
        start_time = time.time()
        data(*args,**kwargs)
        stop_time = time.time()
        print('The function runs %s seconds'%(stop_time - start_time))
    return wrapper
@timmer
def func():
    s = 1
    l = []
    for i in range(1,random.randrange(1,50)):
        s *= i               # s的最大值为:s = 1 * 2 ...* 50
        time.sleep(0.05)
        l.append(i)          # 再把变量i添加至列表l里,此时l列表中的元素最大值为l = [1,2,3...50]
    print("%s‘sproduct is:%d"%(l,s))
func()

输出结果:

例:

[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, 39]‘sproduct is20397882081197443358640281739902897356800000000
The function runs 2.407280206680298 seconds
View Code

相关文章:

  • 2021-11-30
  • 2021-12-06
  • 2021-12-16
  • 2021-11-04
  • 2021-06-23
  • 2021-06-01
  • 2021-11-07
  • 2021-11-25
猜你喜欢
  • 2021-11-11
  • 2021-11-01
  • 2021-06-19
  • 2022-03-05
  • 2021-08-14
  • 2021-07-06
  • 2021-06-07
相关资源
相似解决方案