在Python中,是否有相当于Java对象进行回忆?
因此,我试图在Python fibonacci(n)功能中进行回忆。
def fib(n, memo = [None] * (fibn+1)):
if memo[n] != None: return memo[n]
if n <= 2: return 1
memo[n] = fib(n-1) + fib(n-2)
return memo[n]
我正在尝试找到一种方法来存储我已经计算的值的解决方案。我对此的临时解决方案是制作列表memo = [none] *(fibn+1)
,如果计算了一个新值:memo [n] = fib(n)。我遇到的问题是,列表大部分是空的,总体上非常低效。我想从此
memo = [none,1,None,2,None,None,等...]
转到
memo = {
3: 2
4: 3
7: 13
}
类似于Java中的对象的类似物品。
So I am trying to do memoization in a python fibonacci(n) function.
def fib(n, memo = [None] * (fibn+1)):
if memo[n] != None: return memo[n]
if n <= 2: return 1
memo[n] = fib(n-1) + fib(n-2)
return memo[n]
I am trying to find a way to store the solutions of values, which I already computed. My temporary solution to that is to make a list memo = [None] * (fibn+1)
and if a new value is computed: memo[n] = fib(n)
. The problem I have with this is that the list is mostly empty and is overall very inefficient. I want to go from this
memo = [None, 1, None, 2, None, None, etc...]
to something like this
memo = {
3: 2
4: 3
7: 13
}
which is just like an object in Java.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Python提供的装饰器可以在
functools
模块中自动缓存结果:Python provides decorators that can cache the results for you automatically in the
functools
module:python dictionary 可用于以这种方式存储key-value对(作为Chepner(作为Chepner)他对这个问题的评论说)。
functools
模块也是一个选项,但是如果要直接访问缓存,则必须使用字典。A Python Dictionary can be used to store key-value pairs in this way (as chepner said in his comment on the question).
The
functools
module is also an option, but if you want to directly access the cache yourself you have to use a Dictionary.