Python 将树中的权重从叶更新到根时出错
我有一个json树Python 将树中的权重从叶更新到根时出错,python,json,algorithm,tree,Python,Json,Algorithm,Tree,我有一个json树 {"reply": 0, "id": 1, "children": [{"reply": 1, "id": 2, "children": [{"reply": 1, "id": 3, "children": [{"reply": 1, "id": 4, "children": []}]}]}, {"reply": 0, "id": 5, "children": []}]} 我必须分配权重,以便从叶到根: 所有叶节点的权重均为0.1 如果节点有一个子节点:则节点的权重将变为其
{"reply": 0, "id": 1, "children": [{"reply": 1, "id": 2, "children": [{"reply": 1, "id": 3, "children": [{"reply": 1, "id": 4, "children": []}]}]}, {"reply": 0, "id": 5, "children": []}]}
我必须分配权重,以便从叶到根:
import json
from collections import deque
def generate_children(tree):
queue = deque()
queue.append((tree, None))
while queue:
node, parent = queue.pop()
children = []
for child in node['children']:
queue.append((child, node['id']))
children.append(child['id'])
parent_of[node['id']]=parent
child_of[node['id']]=children
no_child_of[node['id']]=len(child_of[node['id']])
yield node['id'], parent, children
f=open('tree_json','r')
for line in f:
tree=json.loads(line)
parent_of={}
child_of={}
no_child_of={}
weight={}
q = list(generate_children(tree))
#assigning weights to leaf
for c in no_child_of.keys():
if no_child_of[c]==0:
weight[c]=0.1
# assigning weight to the parent
for w in weight.keys():
par=parent_of[w]
n=len(child_of[par])
if n > 1:
weight[par]=0.2
for i in range(n):
weight[par]=weight[par]*weight[child_of[par][i]]
我认为在您的代码中,您试图访问尚未分配的节点的权重 检查以下伪代码。希望它能解决你的问题。 我假设你知道根元素
for each node in tree
weight[node] = 0;
current_node = root;
while(weight[root] = 0){
if(no_child_of(current_node) = 0){
weight[current_node] = 0.1;
current_node = parent_of[current_node];
}else{
boolean all_child_weighted = true;
total_weight = 1;
for each (child[i] of current_node){
if(weight[child_of[current_node][i]] = 0){
all_child_weighted = false;
current_node = child_of[current_node][i];
break;
}else{
total_weight = total_weight * weight[child_of[current_node][i]];
}
}
if(all_child_weighted){
if(no_child_of(current_node) = 1){
weight[current_node] = 0.1*weight[child_of[current_node][1]];
}else{
weight[current_node] = total_weight * 0.1 * 0.2;
}
current_node = parent_of(current_node);
}
}
}
您是否可以编辑您的问题,以包含
节点
、父节点
和子节点
的最小示例,这样我们就可以重新创建您的keyerror。@Martin Evans:当它试图更新根的权重时,以及当它的一个子节点的权重未知时,问题就会出现。请帮忙,我是斯图克。马丁要求你提供一份工作。到目前为止,您提供的代码是不完整的(您没有显示节点
,父节点
,子节点
实际上是什么),这意味着我们无法运行它来重现您的问题哦,而且-当您“获得一个keyrerror”时,会抛出一个异常,您应该会看到一个带有行号的堆栈跟踪。如果不清楚,请显示异常和堆栈跟踪,并指出代码中与行号相对应的行。@Martin Evans:给出完整的代码和输入。请help@Somabatra:root可以有任意数量的子级。在您给出的伪代码中,似乎root只有两个子元素。如果root有n个子元素,请编辑。这将考虑rootI的两个子节点。我刚刚按照您的陈述“如果一个节点有两个或更多子节点,则该节点的权重为:其子节点的权重1*子节点的权重2*0.1*0.2”,并根据您的要求进行编辑。将尝试代码并让您知道。再次感谢,这不起作用,因为它从不为叶节点分配权重。在第一个If条件中,它检查根数是否为零。