在python中为节点指定权重时出现关键错误

在python中为节点指定权重时出现关键错误,python,tree,Python,Tree,我有一个具有以下路径的图: {45,412,460,462},{45,457} 我必须分配权重,以便从叶到根: 所有叶节点的权重均为A 如果节点有一个子节点:则节点的权重将变为其单个子节点的*权重 如果节点有两个或多个子节点,则该节点的权重为: weight of its child1\*weight of child2\*A\*B 例如,输出是节点的最终权重: 462: A, 457: A, 460: A\*A, 412: (A\*A\*A) , 45: A\*B(A\*A\*A\*A)

我有一个具有以下路径的图:

{45,412,460,462},{45,457}
我必须分配权重,以便从叶到根:

  • 所有叶节点的权重均为
    A

  • 如果节点有一个子节点:则节点的权重将变为其单个子节点的*权重

  • 如果节点有两个或多个子节点,则该节点的权重为:

    weight of its child1\*weight of child2\*A\*B
    
    例如,输出是节点的最终权重:

    462: A, 457: A, 460: A\*A, 412: (A\*A\*A) , 45: A\*B(A\*A\*A\*A)
    
  • 我正在使用python中的一个代码,我得到了一个keyrerror 412

    我有三本字典:

    parent_of[node['id']]=parent # parent of a node as value
    child_of[node['id']]=children # the list of children of a node
    no_child_of[node['id']]=len(child_of[node['id']]) # number of children
    
    #assigning weights to leaf
    for c in no_child_of.keys():
        if no_child_of[c]==0:
            weight[c]=A
    # assigning weight to the parent
    for w in weight.keys():
        par=parent_of[w]
        n=len(child_of[par])
        if n > 1:
            weight[par]=B
            for i in range(n):
                weight[par]=weight[par]*weight[child_of[par][i]]
    

    让我们假设将权重分配给父节点的循环从节点457开始
    par
    然后是45,它有多个子项,因此内部
    for
    循环尝试获取这些子项的权重
    weight
    包含子节点457的值,但显然还没有包含另一个子节点412的值。因此出现了
    键错误

    我看不出你的循环方法是如何将权重分配给叶节点的直接父节点以外的其他节点的

    像这样的问题通常通过递归来解决。比如说:

    from operator import mul
    
    
    def assign_weights(parent_of, children_of, a_value, b_value):
        weight_of = dict()
    
        def calculate_weight(node):
            weight = weight_of.get(node)
            if weight is None:
                children = children_of[node]
                weight = reduce(
                    mul,
                    (calculate_weight(c) for c in children),
                    a_value * (b_value if len(children) > 1 else 1)
                )
            weight_of[node] = weight
            return weight
    
        for root in (node for node, parent in parent_of.items() if parent is None):
            calculate_weight(root)
    
        return weight_of
    
    
    def main():
        # 
        # Data for a tree described by two paths (root to leaf):
        # [45, 412, 460, 462] and [45, 457].
        # 
        parent_of = {45: None, 412: 45, 460: 412, 462: 460, 457: 45}
        children_of = {45: [412, 457], 412: [460], 460: [462], 462: [], 457: []}
        print(assign_weights(parent_of, children_of, 23, 42))
    
    
    if __name__ == '__main__':
        main()