gpt4 book ai didi

python - 使用类在 python 中创建图形数据结构

转载 作者:行者123 更新时间:2023-12-01 09:01:04 27 4
gpt4 key购买 nike

我正在尝试创建某种类型的类,该类足够通用,可用于树和图。

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

def add_child(self, child):
self.children.append(child)

def add_children(self, list_of_children):
for child in list_of_children:
self.add_child(child)

def letterGraph():
a = Node('A')
b = Node('B')
c = Node('C')
d = Node('D')
c = Node('C')
e = Node('E')
f = Node('F')
g = Node('G')

a.add_children([b, c])
b.add_children([a, d, e])
c.add_children([a, d])
d.add_children([b, c, e, g, f])
e.add_children([b, d, g])
f.add_children([d, g])
g.add_children([e, d, f])

return a

它似乎在树上工作得很好,但对于图来说,当它向当前节点添加一个子节点时,它也会将同一个子节点添加到当前节点的子节点中。

example:

current_node: a

a.add_children([b,c])

current_node.children: [b,c]

b.children: [b,c]`

最佳答案

我个人根本不会在构造函数中调用它。你不使用那你为什么要把它放在那里呢?

使用__repr__也有助于使其在测试时更具可读性。

class Node:
def __init__(self, value): # Take children out of constructor
self.value = value
self.children = [] # Initialise children in the function

def add_child(self, child):
self.children.append(child)

def add_children(self, list_of_children):
for child in list_of_children:
self.add_child(child)

def __repr__(self):
return self.value # I am not a machine

def letterGraph():
a = Node('A')
b = Node('B')
c = Node('C')
d = Node('D')
c = Node('C')
e = Node('E')
f = Node('F')
g = Node('G')

a.add_children([b, c])
b.add_children([a, d, e])
c.add_children([a, d])
d.add_children([b, c, e, g, f])
e.add_children([b, d, g])
f.add_children([d, g])
g.add_children([e, d, f])

print(a.children)
print(b.children)


letterGraph()

关于python - 使用类在 python 中创建图形数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52453028/

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