我希望能将带有可变参数(Pandas Series对象)的函数进行记忆化。是否有任何方法可以实现这一点?
以下是一个简单的斐波那契数列示例,其中参数是一个Pandas Series对象,第一个元素表示序列的索引。
示例:
以下是一个简单的斐波那契数列示例,其中参数是一个Pandas Series对象,第一个元素表示序列的索引。
示例:
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n.iloc[0] == 1 or n.iloc[0] == 2:
return 1
min1 = n.copy()
min1.iloc[0] -=1
min2 = n.copy()
min2.iloc[0] -= 2
return fib(min1) + fib(min2)
调用函数:
fib(pd.Series([15,0]))
结果:
TypeError: 'Series' objects are mutable, thus they cannot be hashed
由于使用目的较为复杂,因此我发布了这个毫无用处但简单明了的示例。
__hash__
方法(或者是一个安全的方法,具有冻结实例的API,以便在冻结之前抛出故障)。 - abarnert