C#中类似Python的记忆化?
在C#中是否有类似的方法来执行以下操作:C#中类似Python的记忆化?,c#,python,memoization,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] @Mem
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)
类备忘录:
定义初始化(self,f):
self.f=f
self.memo={}
定义调用(self,*args):
如果self.memo中没有参数:
self.memo[args]=self.f(*args)
返回self.memo[args]
@回忆
def纤维(n):
如果n<2:
返回n
其他:
返回fib(n-1)+fib(n-2)
您可以使用词汇表手动执行此操作:
publicstaticintfibonacci(intx)
{
var t=新字典();
Func=null;
fibCached=n=>
{
如果(t.ContainsKey(n))返回t[n];
if(n)“=>”是做什么的?如果你能解释一下你在这段代码中做了什么,那么非python用户很容易回答你的问题question@Kyle我使用python中的decorator缓存函数调用的结果。
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);
}