Pick an order off the shelves
A picker needs a quantity of one part, and it is spread across several shelves. Walk the shelves in the order given and take what you can from each until the order is filled.
- Take as much as a shelf holds, but never more than is still needed.
- Skip shelves that would contribute nothing.
- If the shelves cannot cover it, take everything they have and stop there.
- A request of zero or less picks nothing.
pick_from_shelves(wanted: int, shelves: list<Shelf>) → list<Pick>
Where you start
def pick_from_shelves(wanted: int, shelves: list[Shelf]) -> list[Pick]:
Worked examples
| Call | Result |
|---|---|
pick_from_shelves(12, [Shelf(code="A1", available=5), Shelf(code="A2", available=0), Shelf(code="B3", available=20)]) | [Pick(code="A1", taken=5), Pick(code="B3", taken=7)] |
pick_from_shelves(4, [Shelf(code="A1", available=10)]) | [Pick(code="A1", taken=4)] |
pick_from_shelves(30, [Shelf(code="A1", available=5), Shelf(code="B3", available=6)]) | [Pick(code="A1", taken=5), Pick(code="B3", taken=6)] |
pick_from_shelves(0, [Shelf(code="A1", available=5)]) | [] |
Hint
Carry a running "still needed" figure and stop as soon as it hits zero.
Reference solution in Python
def pick_from_shelves(wanted: int, shelves: list[Shelf]) -> list[Pick]:
out = []
need = wanted
for s in shelves:
if need <= 0:
break
take = min(need, s.available)
if take <= 0:
continue
out.append(Pick(code=s.code, taken=take))
need -= take
return out