1.为函数写一个装饰器,把函数的返回值 +100 然后再返回
例如
@add_hundred
def add(a, b):
return a + b
res = add(17, 13)
print(res) # 结果为 130
def add_hundred(func):
def inner(a,b):
a=a+100
return func(a,b)
return inner
@add_hundred
def add(a,b):
return a + b
print(add(17,13))
2.写一个生成器能够产生1-10中所有半径是偶数的圆的面积
generator=(3.14*x**2 for x in range(1,11) if x%2==0)
print(generator,type(generator))
print(next(generator))
print(next(generator))
print(next(generator))
print(next(generator))
print(next(generator))
#或者
def gen():
for i in range(1,11):
if i % 2==0:
yield 3.14*i**2
g1=gen()
print(g1)
print(next(g1))
print(next(g1))
print(next(g1))
print(next(g1))
print(next(g1))
3.编写一个递归函数,求指定数的阶乘
例如:5的阶乘就是5*4*3*2*1
def factorial(num):
if num==1:
return 1
else:
return factorial(num-1)*num
print(factorial(5))
4.写出你对今日授课内容中有疑问的地方(或者觉得有困难的知识点)
1.利用递归完成下面规律的实现
def fold(digit, num):
pass
fold(1, 2) ----> 2
fold(2, 2) -----> 22 2*10**(2-1)+ fold(1, 2)
fold(3, 2) -----> 222 2*10**(3-1)+ fold(2, 2)
fold(4, 2) -----> 2222 num*10**(digit-1)+ fold(digit-1, num)
注:num只考虑1到9的数字
def fold(digit, num):
if digit==1:
return num
else:
return num*10**(digit-1)+ fold(digit-1, num)
print(fold(9,9))
2.写一个可以产生学号的生成器, 生成的时候可以自定制学号数字位的宽度和学号的开头
例如:
study_id_creater('py',5) -> 依次产生: 'py00001', 'py00002', 'py00003',....'py99999'
study_id_creater('test',3) -> 依次产生: 'test001', 'test002', 'test003',...,'test999'
def study_id_creater(str1: str,n:int):
for i in range(1, 10**(n-1)):
yield str1 + (n - len(str(i))) * '0' + str(i)
stu = study_id_creater("py", 5)
for _ in range(1000):
print(next(stu))
#或者
def study_id_creater(str1: str,n:int):
for i in range(1, 10**(n-1)):
yield str1 + str(i).zfill(n)
stu = study_id_creater("py", 5)
for _ in range(1000):
print(next(stu))
3.写一个装饰器,功能是计算指定功能的运行时间
例如:
@get_time
def table(): # 打印九九乘法表的功能
for r in range(1, 10):
for c in range(1, r + 1):
print('{}*{}={}'.format(c, r, r*c), end="\t")
print()
# 添加装饰器之后
table()
#结果:
1*1=1
1*2=2 2*2=4
.....
1*9=9 2*9=18 3*9=27 .... 9*9=81
执行时间是:....
import time
def count_time(func):
def fun_time(*args):
t1=time.time()
func(*args)
t2=time.time()
print("执行时间是:",t2-t1) #round
return fun_time
@count_time
def table():# 打印九九乘法表的功能
for r in range(1,10):
for c in range(1,r+1):
print("{}*{}={}".format(c,r,c*r),end="\t")
print()
table()