Purchase Line-Item Cost Calculator with Validation
SQL & DataAuto-graded · 24 test casesLast updated
Tests data validation, numeric robustness, error handling, aggregation, and sorting in a billing calculation task
You are building a billing calculator that processes purchase orders. Your task is to compute the total cost and per-item breakdown for a list of line items, with full validation and optional sorting.
Write a function calculate_line_costs(items, unit_prices, sort_by_cost=False) that:
Inputs:
items: a list of dictionaries, each with keys"product_id"(string) and"qty"(numeric)unit_prices: a dictionary mapping product ID strings to unit prices (numeric, nonnegative)sort_by_cost: a boolean flag (defaultFalse)
Returns:
A tuple (total, breakdown) where:
totalis a float representing the sum of all line-item costsbreakdownis a list of dictionaries, one per input item, each containing:"product_id": the product ID (string)"qty": the quantity (preserves the original value)"unit_price": the unit price as a float"cost": the line-item cost (qty * unit_price)
Behavior:
-
Validation rules (fail immediately with a descriptive
ValueError):itemsmust be a list;unit_pricesmust be a dict;sort_by_costmust be a bool- Every product ID in both
itemsandunit_pricesmust be a string - Every unit price must be numeric (not a boolean), finite, and nonnegative
- Every quantity must be numeric (not a boolean), finite, and nonnegative (zero is allowed)
- Each item must be a dictionary containing
"product_id"and"qty"keys - If a product ID appears in
itemsbut not inunit_prices, raise an error - If computing
qty * unit_priceor the running total produces a non-finite result (overflow), raise an error
-
Duplicate product IDs: treat each row as a separate line item; do not merge duplicates
-
Sorting:
- If
sort_by_costisFalse, preserve the input order inbreakdown - If
sort_by_costisTrue, sortbreakdownbycostdescending; ties preserve input order
- If
-
Rounding: do not round; return raw float values
Constraints
- 0 ≤ len(items) ≤ 10,000
- 0 ≤ len(unit_prices) ≤ 10,000
- All numeric values are finite and nonnegative when valid
- Product IDs are nonempty strings
- The function must validate all prices in
unit_pricesbefore processing any line item
Examples
Example 1
Input: calculate_line_costs([{'product_id': 'apple', 'qty': 2}, {'product_id': 'banana', 'qty': 3}, {'product_id': 'apple', 'qty': 1}], {'apple': 1.5, 'banana': 2})
Output: [10.5, [{'product_id': 'apple', 'qty': 2, 'unit_price': 1.5, 'cost': 3}, {'product_id': 'banana', 'qty': 3, 'unit_price': 2, 'cost': 6}, {'product_id': 'apple', 'qty': 1, 'unit_price': 1.5, 'cost': 1.5}]]
Example 2
Input: calculate_line_costs([{'product_id': 'book', 'qty': 2}, {'product_id': 'pen', 'qty': 10}, {'product_id': 'bag', 'qty': 1}], {'book': 12.5, 'pen': 1.25, 'bag': 30}, True)
Output: [67.5, [{'product_id': 'bag', 'qty': 1, 'unit_price': 30, 'cost': 30}, {'product_id': 'book', 'qty': 2, 'unit_price': 12.5, 'cost': 25}, {'product_id': 'pen', 'qty': 10, 'unit_price': 1.25, 'cost': 12.5}]]
Example 3
Input: calculate_line_costs([], {})
Output: [0, []]
Example 4
Input: calculate_line_costs([{'product_id': 'item', 'qty': 0}, {'product_id': 'item', 'qty': 4}], {'item': 2.5})
Output: [10, [{'product_id': 'item', 'qty': 0, 'unit_price': 2.5, 'cost': 0}, {'product_id': 'item', 'qty': 4, 'unit_price': 2.5, 'cost': 10}]]
Hints
Hint 1
Check for booleans explicitly: in Python, bool is a subclass of int, so isinstance(True, Real) returns True
Hint 2
Validate the entire price table first so that corrupt prices are caught even if no line item references them
Hint 3
Use math.isfinite to reject NaN, inf, and -inf in a single check; note that NaN < 0 evaluates to False
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem tests careful contract definition more than algorithmic sophistication. The arithmetic is straightforward; the challenge is pinning down every edge case before writing code.
The solution proceeds in three phases:
Phase 1: Validate the input containers and the entire price table.
Check that items is a list, unit_prices is a dict, and sort_by_cost is a bool. Then walk through every entry in unit_prices: each product ID must be a string, and each price must be numeric (but not a boolean), finite, and nonnegative. Store the normalized float prices in a local dictionary. This upfront validation catches corrupted price data even when no line item references the bad entry.
Phase 2: Process each line item in input order.
For each item, validate that it is a dictionary with a string product ID and a numeric (non-boolean), finite, nonnegative quantity. Look up the unit price, compute the cost as qty * unit_price, and verify the result is finite. Add the cost to the running total and check that the total remains finite. Append a breakdown record with the product ID, original quantity, unit price, and computed cost.
Phase 3: Optionally sort the breakdown.
If sort_by_cost is True, sort the breakdown list by the "cost" field in descending order using a lambda key. Python's sort is stable, so ties preserve their original input order.
Key Decisions
- Missing product ID: raise a
ValueError. Silently skipping or defaulting to zero would under-charge customers without notice. - Booleans: explicitly reject them. In Python,
isinstance(True, Real)returnsTruebecauseboolis a subclass ofint. Without theisinstance(x, bool)guard,Truewould be accepted as quantity 1. - NaN and infinity: use
math.isfiniteto reject them. Note thatnan < 0evaluates toFalse, so a simple comparison would let NaN slip through. - Overflow: check after each multiplication and addition. Two finite inputs can produce infinity (e.g.,
1e200 * 1e200). - Duplicates: keep each row as a separate line. The total sums them correctly, and the breakdown mirrors the input one-to-one.
- Rounding: none. Costs and totals are raw floats; rounding to cents is the caller's responsibility.
Why It Is Correct
The upfront validation of the price table ensures that every product ID and price is well-formed before any line item is processed. The per-row validation ensures every quantity is valid and every product is priced. The overflow checks guarantee that the function never returns a non-finite result. The stable sort ensures deterministic output when costs are equal.
Complexity
- Time: O(P + n) to validate prices and process line items, where P is the size of
unit_pricesand n is the number of items. Add O(n log n) whensort_by_costisTrue. - Space: O(P) for the normalized price map plus O(n) for the breakdown list.
Edge Cases
- Empty input: returns
(0.0, []) - Zero quantity: valid; produces a line with cost 0.0
- Duplicate product IDs: each kept as a separate line
- Large finite values: accepted; overflow to infinity raises an error
- Float imprecision:
0.1 * 3gives0.30000000000000004; tests should use tolerance or the caller should round for display
import math
from numbers import Real
from typing import List, Dict, Tuple
def calculate_line_costs(items: List[Dict], unit_prices: Dict[str, float], sort_by_cost: bool = False) -> Tuple[float, List[Dict]]:
if not isinstance(items, list):
raise ValueError("items must be a list")
if not isinstance(unit_prices, dict):
raise ValueError("unit_prices must be a dictionary")
if not isinstance(sort_by_cost, bool):
raise ValueError("sort_by_cost must be a boolean")
prices = {}
for product_id, price in unit_prices.items():
if not isinstance(product_id, str):
raise ValueError("unit_prices product IDs must be strings")
if isinstance(price, bool) or not isinstance(price, Real):
raise ValueError(f"Invalid price for product {product_id!r}: price must be numeric")
if not math.isfinite(price) or price < 0:
raise ValueError(f"Invalid price for product {product_id!r}: price must be finite and nonnegative")
prices[product_id] = float(price)
total = 0.0
breakdown = []
for index, item in enumerate(items):
if not isinstance(item, dict):
raise ValueError(f"Invalid row {index}: expected a dictionary")
product_id = item.get("product_id")
qty = item.get("qty")
if not isinstance(product_id, str):
raise ValueError(f"Invalid row {index}: product_id must be a string")
if product_id not in prices:
raise ValueError(f"Invalid row {index}: missing price for product {product_id!r}")
if isinstance(qty, bool) or not isinstance(qty, Real):
raise ValueError(f"Invalid row {index}: qty must be numeric")
if not math.isfinite(qty) or qty < 0:
raise ValueError(f"Invalid row {index}: qty must be finite and nonnegative")
cost = float(qty) * prices[product_id]
if not math.isfinite(cost):
raise ValueError(f"Invalid row {index}: computed cost is not finite")
total += cost
if not math.isfinite(total):
raise ValueError(f"Invalid row {index}: running total is not finite")
breakdown.append({"product_id": product_id, "qty": qty, "unit_price": prices[product_id], "cost": cost})
if sort_by_cost:
breakdown.sort(key=lambda item: item["cost"], reverse=True)
return (total, breakdown)