【发布时间】:2020-11-03 15:38:07
【问题描述】:
我在这个link的excel文件中有一个表格:
如果Input 的值为1s,我如何将其读取为n 叉树并总结Python 中的所有节点?如果nodes和leaves的名字也显示在树上会更好。
15
/ \
8 7
/ \ / \
6 2 2 5
/ | \ | / \ / | \
3 3 0 2 2 0 0 2 3
非常感谢您的热心帮助。
我的试用码:
class Node:
def __init__(self, name, weight, children):
self.children = children
self.weight = weight
self.weight_plus_children = weight
def get_all_weight(self):
if self.children is None:
return self.weight_plus_children
else:
for child in self.children:
# print(child)
print("Child node score", child.get_weigth_with_children())
self.weight_plus_children += child.get_weigth_with_children()
return self.weight_plus_children
def get_weigth_with_children(self):
return self.weight_plus_children
leaf1 = Node('Evaluation item 1', 3, None)
leaf2 = Node('Evaluation item 2', 3, None)
leaf3 = Node('Evaluation item 3', 3, None)
leaf4 = Node('Evaluation item 4', 1, None)
leaf5 = Node('Evaluation item 5', 1, None)
leaf6 = Node('Evaluation item 6', 2, None)
leaf7 = Node('Evaluation item 7', 2, None)
leaf8 = Node('Evaluation item 8', 2, None)
subroot1 = Node('Ordinary account authentication', 0, [leaf1, leaf2])
subroot2 = Node('Public account identity verification', 0, [leaf3, leaf4, leaf5, leaf6])
subroot3 = Node('Platform equipment information record', 0, [leaf7, leaf8])
root1 = Node('User Management', 0, [subroot1, subroot2])
root2 = Node('Business platform deployment', 0, [subroot3])
root = Node('Business application security', 0, [root1, root2])
print(subroot1.get_all_weight())
print(subroot2.get_all_weight())
print(subroot3.get_all_weight())
print(root1.get_all_weight())
print(root2.get_all_weight())
print(root.get_all_weight())
输出:
Child node score 3
Child node score 3
6
Child node score 3
Child node score 1
Child node score 1
Child node score 2
7
Child node score 2
Child node score 2
4
Child node score 6
Child node score 7
13
Child node score 4
4
Child node score 13
Child node score 4
17
【问题讨论】:
-
不知道你是如何将那张桌子变成这棵树的。您可能想edit 并使其更清楚。
-
我更新问题,请检查。
标签: python python-3.x algorithm recursion binary-tree