diff --git "a/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Wong/\347\254\254\344\270\211\345\221\250\347\254\254\344\270\211\350\257\276.py" "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Wong/\347\254\254\344\270\211\345\221\250\347\254\254\344\270\211\350\257\276.py" new file mode 100644 index 0000000000000000000000000000000000000000..67a6c751ef541e12471de918263f123133230ab7 --- /dev/null +++ "b/\347\254\254\344\272\214\346\234\237\350\256\255\347\273\203\350\220\245/2\347\217\255/2\347\217\255_Wong/\347\254\254\344\270\211\345\221\250\347\254\254\344\270\211\350\257\276.py" @@ -0,0 +1,69 @@ +#作业一、作用域之间的转换 +a = 10 + +def foo(): + global a #局部变脸转换成全局变量 + a = 11 + print(a) + +foo() +print(a) + + +def foo(): + total = 0 + count = 0 + + def foo_1(value): + nonlocal total, count #局部变量转换成自由变量 + total += value + count += 1 + return total / count + + return foo_1 + +my_avg = foo() +print(my_avg(5)) +print(my_avg(8)) + + +#作业二、使用装饰器输出函数执行时间 + +import time + +def clock_it_deco(func): + def wrapper(*args, **kwargs): + start_time = time.time() + result = func(*args, **kwargs) + end_time = time.time() + print(f"{func.__name__} execute time: {format(end_time - start_time, '.2f')} s") + return result + return wrapper + +@clock_it_deco +def foo(a, b): + count = 1 + while True: + if count > a ** b: + break + count += 1 + +foo(10, 6) + + +#三、为斐波那契数列增加缓存 +def cache_deco(func): + a = {} + def wrapper(*args): + if args not in a: + result = func(*args) + return result + return wrapper + +@cache_deco +def f(n): + if n <= 1: + return 1 + return f(n - 1) + f(n - 2) + +print(f(10))