Python喜欢C#中的memoization?

时间:2013-10-11 09:56:30

标签: c# python memoization

C#中是否有类似的方法来执行以下操作:

class Memoize:
    def __init__(self, f):
        self.f = f
        self.memo = {}
    def __call__(self, *args):
        if not args in self.memo:
            self.memo[args] = self.f(*args)
        return self.memo[args]

@Memoize
def fib(n):
    if n < 2:
        return n
    else:
        return fib(n-1) + fib(n-2)

1 个答案:

答案 0 :(得分:0)

您可以使用Dictionnary<int, int>

手动执行此操作
public static int Fibonacci(int x)
{
    var t = new Dictionary<int, int>();
    Func<int, int> fibCached = null;
    fibCached = n =>
    {
        if (t.ContainsKey(n)) return t[n];
        if (n <= 2) return 1;
        var result = fibCached(n – 2) + fibCached(n – 1);
        t.Add(n, result);
        return result;
    };
    return fibCached(x);
}