我已經寫了一個邏輯找到位置可用數量字典中的相對量, 的位置和數量與字典管理:查找
d={'loc2': 500.0, 'loc3': 200.0, 'loc1': 1000.0, 'loc4': 100.0, 'loc5': 50.0}
from operator import itemgetter
def find_combination(locs,qty):
locs = sorted(locs.items(),key=itemgetter(1),reverse=True)
result = []
for loc,val in locs:
if qty <= 0:
break
elif qty - val >= 0:
qty -= val
result.append((loc,val))
return result
現在,當量變的最大數量如下該字典它給這些意想不到的結果:
print find_combination(d,1000)
[('loc1', 1000.0)]
print find_combination(d,750)
[('loc2', 500.0), ('loc3', 200.0), ('loc5', 50.0)]
print find_combination(d,1900)
[('loc1', 1000.0), ('loc2', 500.0), ('loc3', 200.0), ('loc4', 100.0), ('loc5', 50.0)]
print find_combination(d,150)
[('loc4', 100.0), ('loc5', 50.0)]
print find_combination(d,34)
[] # unexpected # should be [('loc5', 50.0)]
print find_combination(d,88)
[('loc5', 50.0)] # should be [('loc4', 100.0)]
你已經忽略了'qty-val <0'的情況。 – BenDundee
你沒有問過這[之前...](http://stackoverflow.com/q/17164496/832621)? –
@sgpc是的,但不滿意答案。看到批准的答案。 – OpenCurious