我已经编写了一个逻辑来查找位置中的可用数量,因为位置和数量是用字典管理的:
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
现在,当数量低于 dict 中的最大数量时,它会给出这些意想不到的结果:
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)]