場所と数量は辞書で管理されているので、場所の在庫を見つけるロジックを書いたのですが、
d={'loc2': 500.0, 'loc3': 200.0, 'loc1': 1000.0, 'loc4': 100.0, 'loc5': 50.0}
def find_combination(locations,qty):
new_list = sorted(locations.items(),key=lambda y: y[1],reverse=True)
result = []
while qty > 0:
min_item = ''
for item in new_list:
if item[0] in result:
continue
new_diff = abs(qty - item[1])
if not min_item or new_diff <= min_diff:
min_item = item[0]
min_diff = new_diff
min_val = item[1]
result.append((min_item ,locations.get(min_item)))
qty = qty - min_val
return result
数量が口述の最大数量を下回ると、予期しない結果が生じます。
print find_combination(d,500)
OUTPUT: [('loc2', 500.0)]
print find_combination(d,1000)
OUTPUT: [('loc1', 1000.0)]
print find_combination(d,750)
OUTPUT: [('loc2', 500.0), ('loc3', 200.0), ('loc5', 50.0)]
print find_combination(d,1800)
OUTPUT: [('loc1', 1000.0), ('loc1', 1000.0)] # unexpected