Find Available Quantity From Dictionary
Solution 1:
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:
foritemin [x forxin new_list if x[1] <= qty]:
Solution 2:
This is what you would want:
d={'loc2': 500.0, 'loc3': 200.0, 'loc1': 1000.0, 'loc4': 100.0, 'loc5': 50.0}
from operator import itemgetter
deffind_combination(locs,qty):
locs = sorted(d.items(),key=itemgetter(1),reverse=True) #get them in descending order
result = []
for loc,val in locs:
if qty <= 0: #if we've reached the target qty then need to look no furtherbreakelif qty - val >= 0: #if we can take the val of a location and not go below zero do so
qty -= val
result.append((loc,val))
return result
Which when you
print find_combination(d,1800)
[('loc1', 1000.0), ('loc2', 500.0), ('loc3', 200.0), ('loc4', 100.0)]
>>>
Solution 3:
Does the following code do what you want? I have used the integer division to keep track of the remaining quantity.
deffind_combination(locations,qty):
new_list = sorted(locations.items(),key=lambda y: y[1],reverse=True)
result = []
for item in new_list:
quotient = int(qty / item[1])
result.extend(quotient*[item])
qty -= quotient*item[1]
return result
EDIT: Since you have used a check if item[0] not in result
, I am assuming that you don't want to repeat any item in the result. In that case, HennyH's answer will work fine. This answer will not work. But if repetition is allowed, then this one would work.
Post a Comment for "Find Available Quantity From Dictionary"