笨鸟编程-零基础入门Pyhton教程

 找回密码
 立即注册

Python 3.2及以后版本

发布者: 笨鸟自学网

我们来实现一个斐波那契计算器,并使用lru_cache

from functools import lru_cache

@lru_cache(maxsize=32)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> print([fib(n) for n in range(10)])
# Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

那个maxsize参数是告诉lru_cache,最多缓存最近多少个返回值。

我们也可以轻松地对返回值清空缓存,通过这样:

fib.cache_clear()

Archiver|手机版|笨鸟自学网 ( 粤ICP备20019910号 )

GMT+8, 2024-7-27 18:07 , Processed in 0.031606 second(s), 17 queries .

© 2001-2020

返回顶部