KatInterview

Purchase Line-Item Cost Calculator with Validation

SQL & DataAuto-graded · 24 test cases
MediumAuto-gradedSQL & Datadata-validationaggregationsorting

Last 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 (default False)

Returns: A tuple (total, breakdown) where:

  • total is a float representing the sum of all line-item costs
  • breakdown is 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:

  1. Validation rules (fail immediately with a descriptive ValueError):

    • items must be a list; unit_prices must be a dict; sort_by_cost must be a bool
    • Every product ID in both items and unit_prices must 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 items but not in unit_prices, raise an error
    • If computing qty * unit_price or the running total produces a non-finite result (overflow), raise an error
  2. Duplicate product IDs: treat each row as a separate line item; do not merge duplicates

  3. Sorting:

    • If sort_by_cost is False, preserve the input order in breakdown
    • If sort_by_cost is True, sort breakdown by cost descending; ties preserve input order
  4. 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_prices before 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