Drill

ProblemsPython › orders

Total a basket that came off a queue

easyordersPython

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.

order_total(lines: list<Line?>) → int

Solve it in the editor →

Where you start

def order_total(lines: list[Line | None]) -> int:
    

Worked examples

CallResult
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

The same problem in another language

More orders problems in Python