如何在Python中修剪子树

发布于 2024-12-01 22:23:48 字数 301 浏览 2 评论 0原文

我(仍然)正在处理 Python 程序中的树结构。 树中的每个节点都有一个字典“children”,其键保存弧信息,值 是子节点。 (每个节点都有一个(parent,parent_arc)对,其中parent是其父节点,parent_arc是父节点链接该节点的弧。)

现在我想修剪一棵子树,其根是节点的子节点N. 假设这个孩子是 N.children[a]。

del N.children[a] 根本不会释放子树占用的内存。我是否必须实现一种方法来删除子树中的每个节点?我该怎么做?我是否需要重新定义节点类以实现高效的子树修剪?

谢谢你!

I am (still) dealing with a tree structure in a Python program.
Each node in a tree has a dictionary "children", whose keys hold arc information, and values
are the child nodes. (And each node has a (parent, parent_arc) pair, where parent is its parent node and parent_arc is the arc by which the parent node link this node.)

Now I want to prune a subtree, whose root is a child of a node N. Say the child is N.children[a].

del N.children[a] simply won't release the memory occupied by the subtree. Do I have to implement a method to delete every node in the subtree? How can I do this ? Do I need to re-define the node class for efficient subtree pruning?

Thank you!

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

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

发布评论

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

评论(1

十雾 2024-12-08 22:23:48

当A->时B和B-> A 你有参考周期。解决这个问题的一个好方法是让子级使用弱引用来指向父级。像这样的事情:

import weakref
class Node():
    parent = None
    child = None
    @property
    def parent(self):
        parent = self._parent()
        if parent is not None:
            return parent
        raise ValueError("parent has been deleted")
    @parent.setter     # python 2.6+
    def parent(self, parent):
        self._parent = weakref.ref(parent)

现在,该节点没有与其父节点的直接链接,当您删除子节点时,它确实会消失*。 (您可能需要对parent_arc使用相同的方法。)

*请注意,即使Python在不存在引用循环的情况下会更快地释放对象,但它可能不会将该内存返还给操作系统。

When A -> B and B -> A you have reference cycles. A good way to get around that is to have the children use weak references to point back to the parent. Something like this:

import weakref
class Node():
    parent = None
    child = None
    @property
    def parent(self):
        parent = self._parent()
        if parent is not None:
            return parent
        raise ValueError("parent has been deleted")
    @parent.setter     # python 2.6+
    def parent(self, parent):
        self._parent = weakref.ref(parent)

Now, the node does not have a direct link to its parent, and when you delete the child it really will go away*. (You may need to use the same method for the parent_arc.)

*Note that even though Python will release the objects more quickly if no reference cycles exist, it may not give that memory back to the OS.

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