1. 程式人生 > >【Python】python 中 的 memoize 和 memoized

【Python】python 中 的 memoize 和 memoized

python 中編寫遞迴函式時,為減少計算時間,需要用到 memoize 或 memoized 功能。

它們的作用是:記憶函式每次執行的結果,當遞迴函式每次遞迴時,若已經計算過子函式,就直接從記憶中的結果獲取,避免重複計算。

在使用這個功能時,一般在程式前面加個 memoized 的類(這個類可以直接複製別人寫好的程式碼)就行,然後在定義遞迴函式時前面加上 @memoized

例如斐波那契函式,沒有使用 memoized 功能的計算時間為 41 秒,使用後計算時間為 0秒。點選此處看原文斐波那契數列的程式碼

memoized 類的程式碼(decorator.py):

import collections
import functools


class memoized(object):
    """Decorator. Caches a function's return value each time it is called.
    If called later with the same arguments, the cached value is returned
    (not reevaluated).
    """
    def __init__(self, func):
        self.func = func
        self.cache = {}
        
    def __call__(self, *args):
        if not isinstance(args, collections.Hashable):
            # uncacheable. a list, for instance.
            # better to not cache than blow up.
            return self.func(*args)
        if args in self.cache:
            return self.cache[args]
        else:
            value = self.func(*args)
            self.cache[args] = value
            return value
        
    def __repr__(self):
        """Return the function's docstring."""
        return self.func.__doc__
    
    def __get__(self, obj, objtype):
        """Support instance methods."""
        return functools.partial(self.__call__, obj)

使用:

#coding: utf-8
from decorators import memoized
def myclass(object):
    @memoized
    def __init__(a,b):
        return a+b