【问题标题】:Cost/Number Rollup In Tree-like structure - Python树状结构中的成本/数字汇总 - Python
【发布时间】:2016-09-13 21:32:34
【问题描述】:

我有一个数据库表,其中每一行都有:

name,
child1,
child1_quantity,
child2, 
child2_quantity,
child3,
child3_quantity,
price

这个表将作为字典列表或字典的字典带入python(没关系)。它看起来像这样:

[{name: A, child1: C1, child1_quantity:2, child2:C2, child2_quantity: 1, child3: C3, child3_quantity:3, price: null},
{name: C1, child1: C1A, child1_quantity:5, child2: C1B, child2_quantity:2, child3: C1C, child3_quantity:6, price: 3},
{name: C2, child1: C2A, child1_quantity:5, child2: C2B, child2_quantity:2, child3: C2C, child3_quantity:10, price: 4},
{name: C3, child1: C3A, child1_quantity:3, child2: C3B, child2_quantity:7, child3: C3C, child3_quantity:15, price: null}]

问题案例: 我希望能够输入组件的名称并获得其价格。如果表中给出了价格,很简单,退货。 如果没有给出价格,我们必须通过添加它的孩子的价格来计算价格 即

(child1 price x child1 qty) + (child2 price x child2 qty) + .....

但是每个孩子可能/可能没有价格。所以我们需要从它的孩子身上找到孩子的总成本,然后把它提出来......一直到我们得到孩子的总价格,然后把它们加起来得到我们的价格感兴趣的成分。我认为这是一种递归类型的问题,但我想不出如何概念化或表示数据以使我的目标成为可能。我可以得到一些线索/指针吗? sql 递归查询不是一个选项。我正在尝试在 python 数据结构或对象中执行此操作。谢谢。

【问题讨论】:

    标签: python recursion conditional rollup


    【解决方案1】:
    def find_price(self, name):
        if self.dictionary[name]["price"]:
            return self.dictionary[name]["price"]
        else:
            #assuming this is in a class...otherwise use global instead of self
            return self.find_price(dictionary[name]["child1"])*dictionary[name]["child1_quantity"] + find_price(self.dictionary[name]["child2"])*self.dictionary[name]["child2_quantity"]#.....etc
    

    这还假设您将数据读入的顶级对象是一个字典,其中除了名称字段之外,名称还用作键。

    【讨论】:

    • 如果您觉得这回答了问题,也请接受回答。
    猜你喜欢
    • 2021-08-20
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2014-07-28
    • 1970-01-01
    • 2010-10-05
    • 1970-01-01
    相关资源
    最近更新 更多