【发布时间】:2015-08-21 11:32:28
【问题描述】:
我有一棵 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
如果一个节点有一个孩子:那么该节点的权重变为0.1*其单个孩子的权重
-
如果一个节点有两个或多个子节点,那么该节点的权重是:
其child1的重量*child2的重量*....childn*0.1*0.2
例如输出是节点的最终权重:
4: 0.1, 5: 0.1, 3: 0.1*0.1, 2: (0.1*0.1*0.1) 1: 0.1*0.2(0.1*0.1*0.1*0.1)`
我正在使用 python 中的代码
我在更新权重时遇到 keyerror 2:
Traceback 例外(最近一次调用最后一次): 文件“cc1.py”,第 42 行,在 重量[par]=重量[par]*weight[child_of[par][i]] 关键错误:2
我有三个字典:
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]]
【问题讨论】:
-
您能否编辑您的问题以包含
node、parent和children的最小示例,这将使我们能够重新创建您的密钥错误。 -
@Martin Evans:当它试图更新根的权重并且它的一个孩子的权重未知时,问题就出现了。请帮忙,我卡住了
-
Martin 要求您提供minimal, complete and verifiable example。到目前为止,您提供的代码不完整(您没有显示
node、parent、children实际上 是),这意味着我们无法运行它来重现您的问题 -
哦,还有 - 当你“得到一个keyerror”时,一个异常被抛出,你应该看到一个带有行号的堆栈跟踪。请显示异常和堆栈跟踪,如果不清楚,请指出代码中与行号对应的行。
-
@Martin Evans:给出带有输入的完整代码。请帮忙
标签: python json algorithm tree