I have the following dictionary:
>>> for key, details in relationships.items(): print key, details[2] ('INVOICE', 'INVOICE') 1 ('INVOICE', 'ORDER2') 0.50000000 ('INVOICE', 'ORDER1') 0.01536410 ('ORDER1', 'ORDER2') 0.05023163 ('INVOICE', 'ORDER4') 0.00573215 ('ORDER4', 'ORDER1') 0.08777898 ('ORDER4', 'ORDER3') 0.01674388
This creates the following hierarchy:
INVOICE -> ORDER2 -> ORDER1 -> ORDER2 -> ORDER4 -> ORDER1 -> ORDER2 -> ORDER3
where each arrow represents the value of details[2] . It is necessary to calculate the final "relationship" of each order with the invoice. Expected Values:
> ORDER1: 0.01586726 (0.0153641 + 0.0877898 x 0.00573215) > ORDER2: 0.50079704 (0.5 + 0.05023163 x 0.0153641 + 0.05023163 x 0.0877898 x 0.00573215) > ORDER3: 0.00009598 (0.01674388 x 0.00573215) > ORDER4: 0.00573215 (0.00573215)
I have the following attempt at a recursive function:
for invoice in final_relationships.keys(): calculate(invoice, invoice, Decimal(1)) def calculate(orig_ord, curr_ord, contribution): for rel_ID, rel_details in relationships.items(): if rel_ID[1] == curr_ord: if orig_ord == curr_ord: contribution = Decimal(1) if rel_ID[0] != rel_ID[1]: contribution = (contribution * rel_details[2]).quantize(Decimal('0.00000001'), rounding=ROUND_HALF_UP) calculate(orig_ord, rel_ID[0], contribution) else: final_relationships[orig_ord] += contribution contribution = Decimal(0)
This correctly calculates all but one of the scripts for ORDER2.
------- ORDER2 1
The problem is on line 7, since the contribution starts from 0.00077176 instead of 0.05023163, because the iteration for ("ORDER1", "ORDER2") does not happen a second time (after line 2). This relationship is INVOICE -> ORDER4 -> ORDER1 -> ORDER2 .
How can I fix this feature? I tried to discard the contribution if "orig_ord" was not processed, but could not figure out where to put it. If all this is stupid, I'm open to re-recording while I do my work.