问题描述
我写了一个逻辑,以查找位置上的可用数量,位置和数量通过字典进行管理,
I have written a logic to find available quantity in location,for the location and quantity is managed with dictionary,
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
现在,当数量小于字典中的最大数量时,它会产生意外的结果,
Now when the quantity is nelow the max qty in the dict it's giving unexpected 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
推荐答案
您能解释一下为什么该输出是意外的吗?将loc1
项附加到result
后,qty
的值将为800
.在下一次迭代中,行new_diff = abs(qty - item[1])
将再次为项loc1
返回最小值(200),因此该项将再次添加到result
中.完成此操作后,qty
将是-200
,因此while
循环将终止.仅当相关数量小于变量qty
时才添加项目吗?如果是这样,您需要更多的逻辑来做到这一点-您可以将for循环更改为:
Could you explain why that output is unexpected? After one loc1
item has been appended to result
, the value of qty
will be 800
. The line new_diff = abs(qty - item[1])
will return a minimal value (200) for the item loc1
again on the next iteration, so that item will be added to result
once again. Once that's been done, qty
will be -200
, so the while
loop will terminate. Should you only be adding items if their associated quantity is smaller than the variable qty
? If so, you need more logic to do that - you could change the for loop to:
for item in [x for x in new_list if x[1] <= qty]:
这篇关于从字典中查找可用数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!