在Python中,是否有相当于Java对象进行回忆?

发布于 2025-02-10 13:30:13 字数 557 浏览 2 评论 0原文

因此,我试图在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

猥琐帝 2025-02-17 13:30:13

Python提供的装饰器可以在functools模块中自动缓存结果:

from functools import lru_cache

@lru_cache
def fib(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    return fib(n - 1) + fib(n - 2)

Python provides decorators that can cache the results for you automatically in the functools module:

from functools import lru_cache

@lru_cache
def fib(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    return fib(n - 1) + fib(n - 2)
苦妄 2025-02-17 13:30:13

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文