递归Python函数中的持久对象

发布于 2024-10-06 02:11:47 字数 170 浏览 1 评论 0原文

我正在尝试编写一个递归函数,该函数需要在递归时存储和修改对象(例如集合)。我应该在函数内使用全局名称吗?另一种选择是修改或继承函数参数的类,以便它可以保留这个持久对象,但我觉得它不太优雅。如果我完全放弃递归,我也可以使用堆栈......

有没有一种Pythonic方法可以做到这一点?发电机可以解决这个问题吗?

I am trying to write a recursive function that needs to store and modify an object (say a set) as it recurses. Should I use a global name inside the function? Another option is to modify or inherit the class of the parameter of the function so that it can keep this persistent object but I don't find it elegant. I could also use a stack if I would forgo the recursion altogether...

Is there a pythonic way of doing this? Could a generator do the trick?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(6

诺曦 2024-10-13 02:11:47

只需通过递归方法传递持久对象即可。

def recursivemethod(obj_to_act_on, persistent_obj=None):

    if persistent_obj == None:
        persistent_obj = set()

    # Act on your object

    return recursivemethod(newobj, persistent_obj)

Just pass through your persistent object through the recursive method.

def recursivemethod(obj_to_act_on, persistent_obj=None):

    if persistent_obj == None:
        persistent_obj = set()

    # Act on your object

    return recursivemethod(newobj, persistent_obj)
清引 2024-10-13 02:11:47

对象通过引用传递。如果您只修改一个对象,则可以在递归函数中执行此操作,并且更改将全局可见。

如果您需要在递归函数内分配变量并在函数返回后查看它,那么您不能只使用 = 分配局部变量。您可以做的是更新另一个对象的字段。

class Accumulator: pass

def foo():
    # Create accumulator
    acc = Accumulator()
    acc.value = 0

    # Define and call a recursive function that modifies accumulator
    def bar(n):
        if (n > 0): bar(n-1)
        acc.value = acc.value + 1
    bar(5)

    # Get accumulator
    return acc.value

Objects are passed by reference. If you're only modifying an object, you can do that from within a recursive function and the change will be globally visible.

If you need to assign a variable inside a recursive function and see it after the function returns, then you can't just assign a local variable with =. What you can do is update a field of another object.

class Accumulator: pass

def foo():
    # Create accumulator
    acc = Accumulator()
    acc.value = 0

    # Define and call a recursive function that modifies accumulator
    def bar(n):
        if (n > 0): bar(n-1)
        acc.value = acc.value + 1
    bar(5)

    # Get accumulator
    return acc.value
一笔一画续写前缘 2024-10-13 02:11:47

将集合作为参数传递到递归方法中,然后在将其传递到下一步之前对其进行修改。复杂对象通过引用传递。

Pass the set into the recursive method as an argument, then modify it there before passing it to the next step. Complex objects are passed by reference.

〆凄凉。 2024-10-13 02:11:47

如果它是一个容器(不是不可变的数据类型),您可以通过以下方式传递对象:(

import random

def foo(bar=None, i=10):
    if bar is None:
        bar = set()
    if i == 0:
        return bar
    bar |= set(random.randint(1, 1000) for i in xrange(10))
    return foo(bar, i - 1)

random_numbers_set = foo()

不要问我那是什么意思......我只是输入随机的东西:P)

If it's a container (not an immutable data type), you can pass the object through:

import random

def foo(bar=None, i=10):
    if bar is None:
        bar = set()
    if i == 0:
        return bar
    bar |= set(random.randint(1, 1000) for i in xrange(10))
    return foo(bar, i - 1)

random_numbers_set = foo()

(Don't ask me what that's meant to do... I was just typing random things :P)

哀由 2024-10-13 02:11:47

如果您传递的对象是可变的,那么在较深的递归中对其进行的更改将在较早的递归中看到。

If the object you pass is mutable then changes to it in deeper recursions will be seen in earlier recursions.

丿*梦醉红颜 2024-10-13 02:11:47
  1. 使用函数的全局变量。

  2. 将对象作为累加器传递:

    def recurse(foo, acc=None):
        ACC = {}
        递归(acc)
    
  1. Use a variable global to the function.

  2. Pass the object around as an accumulator:

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