python - 使用类在python中创建图形数据结构
问题描述
我正在尝试创建某种类型的类,该类足够通用,可用于树和图。
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
它似乎适用于树,但对于图形,当它向当前节点添加一个子节点时,它也会将同一个子节点添加到当前节点的子节点。
例子:
当前节点:一个
a.add_children([b,c])
current_node.children:[b,c]
b.儿童:[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()
推荐阅读
- c++ - 是否可以从容器完善转发到值类型?
- node.js - SQL Server/ TypeORM - 多个连接。我应该如何格式化查询?
- c# - Hololens - UserConsentVerifier 不适用于 Hololens 第一代
- sed - 如何grep一个具有变化值的句子
- javascript - 两种在JS中创建SVG的方法,哪个更安全?
- html - 如何使我的物化文本区域不被切断?
- python - 小写和大写字母之前和之后
- javascript - 为什么将带括号的函数传递给“addListener”会导致它只触发一次?
- nativescript - Nativescript ng g '@schematics/angular/utility/config' 错误
- javascript - PathItems 生成 Undefined is not an object in photoshop scripting