runtime
397 / 500
question 397 Software Architecture · medium

The invoice calculation as a pure core

An invoicing script mixed database reads, arithmetic and PDF output. Write its core, invoice_totals(lines, prices, tax_rate): pure arithmetic over plain data, no I/O, so it can be tested and reused for the PDF and the API.

Functioninvoice_totals(lines, prices, tax_rate)
linesa list of {"sku": ..., "qty": ...}; prices maps SKU to unit price
Returns{"subtotal": s, "tax": t, "total": s + t}, each rounded to 2 decimals (round the subtotal and tax first, then add)
RaisesKeyError for a SKU with no price
Examples
callinvoice_totals([{'sku': 'SPO-11681', 'qty': 2}, {'sku': 'HOM-22847', 'qty': 1}], {'SPO-11681': 7.49, 'HOM-22847': 31}, 0.0825)returns{'subtotal': 45.98, 'tax': 3.79, 'total': 49.77}
callinvoice_totals([], {'SPO-11681': 7.49}, 0.1)returns{'subtotal': 0, 'tax': 0.0, 'total': 0.0}
callinvoice_totals([{'sku': 'A', 'qty': 3}], {'A': 10}, 0)returns{'subtotal': 30, 'tax': 0, 'total': 30}

Loading your progress…

The invoice calculation as a pure core — Python practice · Runtime