Total a basket that came off a queue
Order lines arrive from a message queue and the payload is not always clean: a line can be missing entirely, and quantities have been seen at zero.
- A missing line contributes nothing and must not stop the sum.
- A line with a quantity of zero or less contributes nothing either.
- The total is in minor units.
order_total(lines: list<Line?>) → int
Where you start
def order_total(lines: list[Line | None]) -> int:
Worked examples
| Call | Result |
|---|---|
order_total([Line(sku="A", qty=2, unit_price=100), Line(sku="B", qty=3, unit_price=50)]) | 350 |
order_total([Line(sku="A", qty=1, unit_price=10), None, Line(sku="C", qty=2, unit_price=5)]) | 20 |
order_total([Line(sku="A", qty=0, unit_price=999), Line(sku="B", qty=-1, unit_price=999)]) | 0 |
order_total([]) | 0 |
Hint
Guard inside the loop, not before it. One bad line should not cost you the rest.
Reference solution in Python
def order_total(lines: list[Line | None]) -> int:
total = 0
for l in lines:
if l is None or l.qty <= 0:
continue
total += l.qty * l.unit_price
return total