Skip to content

Commit e40f6a4

Browse files
committed
add cached fib function
1 parent da8ed9c commit e40f6a4

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

README.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2651,6 +2651,37 @@ def fibonacci(n):
26512651
return next(fibs)
26522652
```
26532653

2654+
**做缓存**
2655+
2656+
```python
2657+
def cache(fn):
2658+
cached = {}
2659+
def wrapper(*args):
2660+
if args not in cached:
2661+
cached[args] = fn(*args)
2662+
return cached[args]
2663+
wrapper.__name__ = fn.__name__
2664+
return wrapper
2665+
2666+
@cache
2667+
def fib(n):
2668+
if n < 2:
2669+
return 1
2670+
return fib(n-1) + fib(n-2)
2671+
```
2672+
2673+
**利用 funtools.lru_cache 做缓存**
2674+
2675+
```python
2676+
from functools import lru_cache
2677+
2678+
@lru_cache(maxsize=32)
2679+
def fib(n):
2680+
if n < 2:
2681+
return 1
2682+
return fib(n-1) + fib(n-2)
2683+
```
2684+
26542685
#### Logarithmic
26552686

26562687
**矩阵**

0 commit comments

Comments
 (0)