我遇到了经典的树问题,找不到合适的解决方案。我有一个用python词典表示的树,有树枝和树叶。我需要计算每个分支的所有子项(price-property)的总和,并将其存储在sum-property中。这是我的树(dict)的样本:
[
{
"id": 1,
"type": "group",
"name": "test-group 1",
"price": 0,
"sum": 0,
"children": [
{
"id": 2,
"type": "position",
"name": "test-inner 1",
"price": 5
},
{
"id": 3,
"type": "position",
"name": "test-inner 2",
"price": 10
}
]
},
{
"id": 4,
"type": "group",
"name": "test-group 2",
"sum": 0,
"children": [
{
"id": 5,
"type": "position",
"name": "test-inner 3",
"price": 5
},
{
"id": 6,
"type": "group",
"name": "test-group 3",
"sum": 0,
"children": [
{
"id": 7,
"type": "position",
"name": "test-inner 4",
"price": 5
},
{
"id": 8,
"type": "position",
"name": "test-inner 5",
"price": 10
}
]
}
]
}
]
我确定我需要递归并且已经找到解决方案来获得整棵树的总和......但我也需要部分总和......
感谢您的帮助!
答案 0 :(得分:0)
假设非叶节点没有价格,就这样做:
def add_sums(tree):
if 'price' in tree:
return tree['price']
s = sum(map(add_sums, tree['children']))
tree['sum'] = s
return s
如果他们确实需要能够有价格(如您的测试数据所示),那么您可以
def add_sums(tree):
if 'children' not in tree:
return tree['price']
s = sum(map(add_sums, tree['children']))
if 'price' in tree:
s += tree['price']
tree['sum'] = s
return s
可能会在更新总和之后将节点价格的添加移动到,如果它应该只是孩子的总和。
答案 1 :(得分:0)
您可以尝试按以下方式进行测试:
def dct_sum(dct):
if isinstance(dct, dict):
if 'price' in dct:
return dct['price']
if 'children' in dct:
dct['sum'] = sum(dct_sum(c) for c in dct['children'])
return dct['sum']
if isinstance(dct, list):
return sum(dct_sum(item) for item in dct)
return 0