Drill

ProblemsPython › inventory

Pick an order off the shelves

mediuminventoryPython

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.

pick_from_shelves(wanted: int, shelves: list<Shelf>) → list<Pick>

Solve it in the editor →

Where you start

def pick_from_shelves(wanted: int, shelves: list[Shelf]) -> list[Pick]:
    

Worked examples

CallResult
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

The same problem in another language

More inventory problems in Python