从叶到根更新树中的权重时出错

时间:2015-08-21 11:32:29

标签: 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": []}]}

我必须分配从叶到根的权重:

  1. 所有叶节点的重量均为0.1

  2. 如果一个节点有一个孩子:那么节点的权重就会变成其单个孩子的0.1 *重量

  3. 如果某个节点有两个或更多子节点,则该节点的权重为:

    孩子的体重1 *孩子的体重2 * ....孩子* 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)`

  4. 我正在使用python中的代码

    我在更新体重时得到了一个keyerror 2:

    例外是Traceback(最近一次调用最后一次):   文件“cc1.py”,第42行,in     重量[面值] =重量[面值] *重量[child_of [面值] [I]] KeyError: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]]
    

1 个答案:

答案 0 :(得分:2)

我认为在您的代码中,您尝试访问尚未分配的节点的权重。

检查以下伪代码。希望它能解决你的目的。 我假设你知道根元素。

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);
      }
   }
}