【发布时间】:2017-05-26 21:13:10
【问题描述】:
我有以下字典:
>>> 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
这将创建以下层次结构:
INVOICE -> ORDER2
-> ORDER1 -> ORDER2
-> ORDER4 -> ORDER1 -> ORDER2
-> ORDER3
每个箭头代表details[2] 的值。需要计算每个订单与发票的最终“关系”。预期值:
> 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)
我对递归函数有以下尝试:
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)
对于 ORDER2,这会正确计算除一种情况外的所有情况。
------- ORDER2
1 # rel_ID, curr_ord, rel_details[2], contribution
2 ('ORDER1', 'ORDER2') ORDER2 0.05023163 1
3 ('INVOICE', 'ORDER1') ORDER1 0.01536410 0.05023163
4 ('INVOICE', 'INVOICE') INVOICE 1 0.00077176
5 # final
6 0.00077176
7 ('ORDER4', 'ORDER1') ORDER1 0.08777898 0.00077176
8 ('INVOICE', 'ORDER4') ORDER4 0.00573215 0.00006774
9 ('INVOICE', 'INVOICE') INVOICE 1 3.9E-7
10 # final
11 0.00077215
12 ('INVOICE', 'ORDER2') ORDER2 0.50000000 0.05023163
13 ('INVOICE', 'INVOICE') INVOICE 1 0.50000000
14 # final
15 0.50077215
问题出在第 7 行,因为贡献从 0.00077176 而不是 0.05023163 开始,因为 ('ORDER1', 'ORDER2') 的迭代不会第二次发生(在第 2 行之后)。这是INVOICE -> ORDER4 -> ORDER1 -> ORDER2的关系。
如何修复该功能?如果未处理“orig_ord”,我尝试重置贡献,但无法弄清楚将其放在哪里。如果整个事情都是愚蠢的,我愿意重写,只要我完成工作。
【问题讨论】:
标签: python python-2.7 recursion