Drill

ProblemsPython › pricing

Which pack size is the best value

mediumpricingPython

The same product sits on the shelf in several pack sizes. A price-comparison badge needs the one with the lowest cost per unit.

cheapest_pack(packs: list<Pack>) → string?

Solve it in the editor →

Where you start

def cheapest_pack(packs: list[Pack]) -> str | None:
    

Worked examples

CallResult
cheapest_pack([Pack(label="single", units=1, price=300), Pack(label="six", units=6, price=1500), Pack(label="crate", units=24, price=6200)])"six"
cheapest_pack([Pack(label="a", units=2, price=200), Pack(label="b", units=4, price=400)])"b"
cheapest_pack([Pack(label="broken", units=0, price=100), Pack(label="ok", units=3, price=900)])"ok"
cheapest_pack([])None

Hint

Cross-multiply instead of dividing: a.price * b.units against b.price * a.units keeps it in integers.

Reference solution in Python
def cheapest_pack(packs: list[Pack]) -> str | None:
    best = None
    for p in packs:
        if p.units <= 0:
            continue
        if best is None:
            best = p
            continue
        a, b = p.price * best.units, best.price * p.units
        if a < b or (a == b and p.units > best.units):
            best = p
    return None if best is None else best.label

The same problem in another language

More pricing problems in Python