CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: jackfrued/Python-100-Days
Path: blob/master/Day16-20/code/example03.py
Views: 729
1
"""
2
函数递归调用 - 函数直接或者间接的调用了自身
3
1. 收敛条件
4
2. 递归公式
5
6
n! = n * (n-1)!
7
f(n) = f(n-1) + f(n-2)
8
1 1 2 3 5 8 13 21 34 55 ...
9
"""
10
from contextlib import contextmanager
11
from time import perf_counter
12
13
14
def fac(num):
15
"""求阶乘"""
16
assert num >= 0
17
if num in (0, 1):
18
return 1
19
return num * fac(num - 1)
20
21
22
def fib2(num):
23
"""普通函数"""
24
a, b = 1, 1
25
for _ in range(num - 1):
26
a, b = b, a + b
27
return a
28
29
30
def fib3(num):
31
"""生成器"""
32
a, b = 0, 1
33
for _ in range(num):
34
a, b = b, a + b
35
yield a
36
37
38
# 动态规划 - 保存可能进行重复运算的中间结果(空间换时间)
39
def fib(num, results={}):
40
"""斐波拉切数"""
41
assert num > 0
42
if num in (1, 2):
43
return 1
44
try:
45
return results[num]
46
except KeyError:
47
results[num] = fib(num - 1) + fib(num - 2)
48
return results[num]
49
50
51
@contextmanager
52
def timer():
53
try:
54
start = perf_counter()
55
yield
56
finally:
57
end = perf_counter()
58
print(f'{end - start}秒')
59
60
61
def main():
62
"""主函数"""
63
# for val in fib3(20):
64
# print(val)
65
# gen = fib3(20)
66
# for _ in range(10):
67
# print(next(gen))
68
for num in range(1, 121):
69
with timer():
70
print(f'{num}: {fib(num)}')
71
# print(fac(5))
72
# print(fac(-5))
73
74
75
if __name__ == '__main__':
76
main()
77
78