diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/4\347\217\255/4\347\217\255_\345\276\267\351\207\214\345\205\213/lesson3-3 homework.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/4\347\217\255/4\347\217\255_\345\276\267\351\207\214\345\205\213/lesson3-3 homework.py" new file mode 100644 index 0000000000000000000000000000000000000000..608969b6b4bac8812c4dcd658f0367d4b40214ac --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/4\347\217\255/4\347\217\255_\345\276\267\351\207\214\345\205\213/lesson3-3 homework.py" @@ -0,0 +1,69 @@ +#问题一,练习作用域之间的转换 +total = 0 +def sum(a, b): + total = a + b + print("函数内是局部变量:", total) + return total +print(sum(5, 10)) +print("函数外是全局变量:", total) + +total1 = 1 +def func(): + global total1 + print(total1) + total1 = 2 + print(total1) +print(func()) +print(total1) + +def a(): + total = 1 + def b(): + nonlocal total + total = 3 + print(total) + return b + b() + print(total) +a() + +#问题二,实现一个装饰器,用来输出函数的执行时间 +import time +def clock_deco(func): + def wrap(*args, **kwargs): + start_time = time.time() + result = func(*args, **kwargs) + end_time = time.time() + print(f"{func.__name__} 执行时长为:{format(end_time - start_time, '.2f')}s") + return result + return wrap + +@clock_deco +def cool(a, b): + num = 0 + while True: + if num >= a ** b: + break + num += 1 + +cool(5, 10) + +#问题三,使用装饰器来为斐波那契函数增加缓存 +a = {} +def cache_deco(func): + global a + def wrap(n): + if n not in a: + a[n] = func(n) + return a[n] + return wrap + +@ cache_deco +def fib(n): + if n < 2: + return n + else: + return fib(n - 2) + fib(n - 1) + +print(fib(10)) +print(a) \ No newline at end of file