gpt4 book ai didi

python - 实现一个 child 和 parent 可以互相引用的树

转载 作者:太空宇宙 更新时间:2023-11-04 08:09:26 32 4
gpt4 key购买 nike

来自 http://cbio.ufs.ac.za/live_docs/nbn_tut/trees.html

Let's create a python class to represent a tree. We need some way to store data in a node, and some way to indicate any child nodes, or subtrees.

class node(object):
def __init__(self, value, children = []):
self.value = value
self.children = children

Whoa! That seems way too easy... but believe it or not, it does the job. Let's use our new class to store our family tree...

tree = node("grandmother", [
node("daughter", [
node("granddaughter"),
node("grandson")]),
node("son", [
node("granddaughter"),
node("grandson")])
]);

我希望能够获得每个 node 实例的子节点和父节点,所以我认为我需要同时定义其父节点和子节点

class node(object):
def __init__(self, value, children = [], parent = []):
self.value = value
self.children = children
self.parent = parent

但问题是每个节点在其每个子节点和父节点中都会有一个副本。如果我更改它的值,我将不得不更改其副本中的所有值。在 C++ 中,没有这样的问题,因为我们可以通过将指向其子节点和父节点的指针仅存储在节点中来引用节点的子节点和父节点。我想知道如何在 Python 中实现这样的树?谢谢。

最佳答案

您可以在节点构造函数中分配 child 的 parent :

class node(object):
def __init__(self, value, children = None):
self.value = value
self.children = children or []
self.parent = None
for child in self.children:
child.parent = self

关于python - 实现一个 child 和 parent 可以互相引用的树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25437376/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com