Python - 装饰器实现缓存

from functools import wraps

def cache(func):
    cache = {}
    @wraps(func)
    def wrap(*args):
        if args not in cache:
            cache[args] = func(*args)
        return cache[args]
    return wrap

class Solution:
    @cache
    def fib(self, N):
        if N < 2:
            return N
        else:
            return self.fib(N - 2) + self.fib(N - 1)

或者

import functools
class Solution:
    @functools.lru_cache(maxsize=None)
    def fib(self, N):
        """
        :type N: int
        :rtype: int
        """
        if N <= 1:
            return N
        else:
            return self.fib(N - 1) + self.fib(N - 2)

猜你喜欢

转载自www.cnblogs.com/allen2333/p/10363388.html