Cost/Number Rollup In Tree-like structure - Python
<p>I have a database table where each row has:</p>

<pre><code>name,
child1,
child1_quantity,
child2, 
child2_quantity,
child3,
child3_quantity,
price
</code></pre>

<p>This table will be brought into python as a list of dictionaries or dictionary of dictionaries (doesn't matter). It will look something like this:</p>

<pre><code>[{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}]
</code></pre>

<p>Problem Case: 
I want to be able to enter component's name and get its price. If a price is given in the table, easy, return it.
If a price is not given, we have to calculate the price by adding the prices of it's children 
i.e </p>

<pre><code>(child1 price x child1 qty) + (child2 price x child2 qty) + .....
</code></pre>

<p>But each child may/may not have a price. So we'll need to go down and find the total cost of the child from its child and then bring it up ..... all until we get the total prices of the children and then sum them up to get the price of our component of interest. It is a recursive type of problem, I think but I cannot think of how to conceptualize or represent the data to make my goal possible. Can I get some clues/pointers?
sql recursive query is not an option. I'm trying to do this in a python data structure or object. Thanks.</p>

<pre><code>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
</code></pre>

<p>this also assumes that the top level object that you read the data into is a diction where the names also serve as keys in addition to their name fields.</p>

python recursion conditional rollup