Which pack size is the best value
The same product sits on the shelf in several pack sizes. A price-comparison badge needs the one with the lowest cost per unit.
- Compare price per unit, not sticker price.
- Skip any pack claiming zero or fewer units — that is bad data, not a bargain.
- On a tie, the larger pack wins.
- With nothing worth comparing, return null.
cheapest_pack(packs: list<Pack>) → string?
Where you start
def cheapest_pack(packs: list[Pack]) -> str | None:
Worked examples
| Call | Result |
|---|---|
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