Object-Oriented Pizza Order Pricing Pipeline
Medium · Software Engineering Fundamentals · Software Engineer · Online Assessment
Problem Statement
Implement an object-oriented checkout pricing engine for a pizza shop consisting of two classes, Pizza and Order, that calculates item totals, runs four promotional rules in strict order against a running balance, and returns an itemized receipt dictionary.
Item Pricing (Pizza)
- Supported sizes and base prices:
"Small":$8.00"Medium":$12.00"Large":$16.00- Passing any other size string to
Pizzashould raiseValueError.
- Each topping string in
toppingsadds$1.50to the pizza's price:pizza_price = base_size_price + 1.50 * len(toppings).
Sequential Promotional Pipeline (Order)
Starting from subtotal (the sum of every pizza's price in the order), maintain a running balance and evaluate Policies "A", "B", "C", and "D" strictly in order. At every stage, clamp the applied deduction to the remaining balance so no intermediate or final balance ever drops below $0.00:
- Policy
"A"— Every Third Pizza Free: Across an order ofnpizzas, then // 3lowest-priced pizzas overall are deducted at100%of their full prices (anyn % 3remainder receives no Policy"A"deduction). - Policy
"B"— Half-Price Toppings on Multi-Large Orders: Whenever the order contains2or more"Large"pizzas, deduct$0.75(50%of$1.50) per topping across every pizza in the order (including toppings on pizzas made free by Policy"A"). - Policy
"C"— High-Spend10%Tier: If the running balance remaining after Policies"A"and"B"is at least$50.00, deduct10%of that remaining balance, rounding to the nearest cent with exact half-cents ($0.005) rounded up (for example,$5.375rounds to$5.38). - Policy
"D"— Promo Code: Ifcoupon_codematches"SAVE5"(exact, case-sensitive string match), deduct$5.00from the remaining balance after Policy"C".
Required Class Signatures & Receipt Structure
class Pizza:
def __init__(self, size: str, toppings: List[str]): ...
def get_price(self) -> float: ...
class Order:
def __init__(self, coupon_code: Optional[str] = None): ...
def add_pizza(self, pizza: Pizza) -> None: ...
def calculate_receipt(self) -> Dict: ...
calculate_receipt() must leave the order's items unchanged and return:
{
"subtotal": float,
"discounts": [{"policy": str, "amount": float}, ...],
"total": float,
}
"policy"is"A","B","C", or"D", listed in evaluation order and including only policies whose applied"amount"is strictly greater than0.00.- Every monetary number is rounded to
2decimal places, satisfyingsubtotal - sum(d["amount"] for d in discounts) == totalto the cent.
Examples
Example 1
order = Order(coupon_code="SAVE5")
order.add_pizza(Pizza("Large", ["olives", "onions", "peppers", "spinach"])) # $22.00
order.add_pizza(Pizza("Large", ["basil", "jalapenos"])) # $19.00
order.add_pizza(Pizza("Small", ["garlic"])) # $9.50
order.calculate_receipt()
# Output:
# {
# "subtotal": 50.5,
# "discounts": [
# {"policy": "A", "amount": 9.5},
# {"policy": "B", "amount": 5.25},
# {"policy": "D", "amount": 5.0},
# ],
# "total": 30.75,
# }
Walk-through: The three pizzas start at $22.00 + $19.00 + $9.50 = $50.50. Policy "A" makes the 3 // 3 = 1 cheapest pizza ($9.50) free, lowering the balance to $41.00. Because there are 2 "Large" pizzas, Policy "B" deducts 7 * $0.75 = $5.25 across all 7 toppings in the order, leaving $35.75. Policy "C" is skipped because $35.75 < $50.00 (even though the initial subtotal exceeded $50.00), and Policy "D" subtracts $5.00 for "SAVE5", yielding $30.75.
Example 2
order = Order()
order.add_pizza(Pizza("Large", ["bacon", "sausage", "ham", "olives", "peppers", "mushrooms"])) # $25.00
order.add_pizza(Pizza("Large", ["spinach", "feta", "tomatoes", "onions", "garlic"])) # $23.50
order.add_pizza(Pizza("Medium", ["basil", "jalapenos"])) # $15.00
order.add_pizza(Pizza("Small", [])) # $8.00
order.calculate_receipt()
# Output:
# {
# "subtotal": 71.5,
# "discounts": [
# {"policy": "A", "amount": 8.0},
# {"policy": "B", "amount": 9.75},
# {"policy": "C", "amount": 5.38},
# ],
# "total": 48.37,
# }
Walk-through: Subtotal is $25.00 + $23.50 + $15.00 + $8.00 = $71.50. Policy "A" deducts the 4 // 3 = 1 cheapest pizza ($8.00 -> $63.50). Policy "B" deducts 13 * $0.75 = $9.75 across all 13 toppings ($63.50 - $9.75 = $53.75). Because $53.75 >= $50.00, Policy "C" computes 10% ($5.375), rounds the half-cent up to $5.38, and leaves $48.37. With no coupon code, Policy "D" is omitted.
Constraints
- Valid
sizevalues are"Small","Medium", and"Large"(raiseValueErrorotherwise). - Each pizza has
0 <= len(toppings) <= 50topping strings. - Each order contains
0 <= n <= 100pizzas. coupon_codeisNoneor an arbitrary string.
Step-by-step walkthrough
Understand the pricing pipeline and rules
We need two classes—
PizzaandOrder—that compute item prices, evaluate four promotional policies sequentially against a running balance, and return an itemized receipt dictionary:Item prices summed --> subtotal | v [ Policy A ] n // 3 lowest-priced pizzas overall are free | v [ Policy B ] 2+ Large pizzas -> $0.75 off every topping in the order | v [ Policy C ] Running balance >= $50.00 -> 10% off remaining balance | v [ Policy D ] Coupon "SAVE5" -> $5.00 off remaining balance | v final total (clamped so balance never drops below $0.00)Pin down the exact edge rules before coding:
- Policy labels and positive-only lines: Each entry in
"discounts"uses"A","B","C", or"D"and appears only when its applied deduction exceeds$0.00. - Policy A inspects the entire basket: Across
npizzas, then // 3lowest-priced pizzas overall are free (not the cheapest within each chronological group of 3), and anyn % 3leftover pizzas get no Policy A deduction. - Policy B counts every topping in the order: Whenever at least 2
"Large"pizzas are present,$0.75is deducted per topping across all pizzas—including toppings on pizzas made free by Policy A. - Policy C checks the post-A/B running balance: As in Example 1, an order whose initial subtotal is
$50.50but drops to$35.75after Policies A and B does not qualify for Policy C. - Zero-dollar floor: At every step, clamp the deduction to the current running balance so neither intermediate nor final balances ever become negative.
- Policy labels and positive-only lines: Each entry in
Why we compute in integer cents instead of floats
Python
floatvalues store base-2 fractions, which cannot represent most decimal cents exactly (0.1 + 0.2 == 0.30000000000000004). Worse, Python'sround(..., 2)uses round-half-to-even on binary approximations (round(51.25 * 0.10, 2)yields5.12, whereasround(53.75 * 0.10, 2)yields5.38), and subtracting rounded floats can makesubtotal - sum(discounts)disagree withtotalby$0.01.Because every menu price and per-topping deduction is an exact whole number of cents (
$8.00=800,$1.50=150,$0.75=75), performing all internal arithmetic inintcents—and converting to dollar floats once at the output boundary—keeps every receipt 100% exact to the penny.SIZE_PRICE_CENTS = { "Small": 800, "Medium": 1200, "Large": 1600, } TOPPING_PRICE_CENTS = 150 TOPPING_DISCOUNT_CENTS = 75 TIER_THRESHOLD_CENTS = 5000 VALID_COUPON_CODE = "SAVE5" COUPON_DISCOUNT_CENTS = 500 def cents_to_dollars(cents: int) -> float: """Convert an exact integer cent amount into a two-decimal dollar float.""" return round(cents / 100, 2)Build the `Pizza` model
Pizzavalidatessize, stores a defensive copy oftoppings(list(toppings)) so later caller mutations cannot alter an already-added pizza's price, and exposesprice_cents() -> intinternally alongside publicget_price() -> float:from typing import List class Pizza: def __init__(self, size: str, toppings: List[str]): if size not in SIZE_PRICE_CENTS: raise ValueError(f"Unknown pizza size: {size!r}") self.size = size # Copy the caller's list so mutating the original list later cannot alter this pizza's price. self.toppings = list(toppings) def price_cents(self) -> int: """Exact pizza price in integer cents: base size price + 150 cents per topping.""" base_cents = SIZE_PRICE_CENTS[self.size] toppings_cents = TOPPING_PRICE_CENTS * len(self.toppings) return base_cents + toppings_cents def get_price(self) -> float: return cents_to_dollars(self.price_cents())Isolate each promotional rule behind one function signature
Giving all four rules one uniform signature—
(pizzas, balance_cents, coupon_code) -> raw_discount_cents—cleanly separates rule math from balance clamping:- Policy A (
policy_a_free_pizzas): Collect all pizza prices in cents, sort ascending, and sum the firstlen(pizzas) // 3values. - Policy B (
policy_b_topping_special): Count"Large"pizzas and total toppings across all pizzas; return75 * total_toppingswhenlarge_count >= 2, else0. - Policy C (
policy_c_tier_percentage): Return0whenbalance_cents < 5000. Otherwise compute10%with half-cents (0.5c) rounded up using pure integer math(balance_cents + 5) // 10:balance_cents = 5374(10%=537.4c) ->(5374 + 5) // 10 = 537c ($5.37).balance_cents = 5375(10%=537.5c) ->(5375 + 5) // 10 = 538c ($5.38).
- Policy D (
policy_d_fixed_coupon): Return500cents whencoupon_code == "SAVE5", else0.
from typing import List, Optional def policy_a_free_pizzas(pizzas: List[Pizza], balance_cents: int, coupon_code: Optional[str]) -> int: """Policy A: Across every 3 pizzas in the order, the lowest-priced pizza overall is free.""" # price_cents_list: ascending list of individual pizza prices in cents, e.g., [950, 1900, 2200]. price_cents_list = [] for pizza in pizzas: price_cents_list.append(pizza.price_cents()) price_cents_list.sort() # Integer division drops leftover pizzas (< 3). free_count = len(price_cents_list) // 3 free_total_cents = 0 for i in range(free_count): free_total_cents += price_cents_list[i] return free_total_cents def policy_b_topping_special(pizzas: List[Pizza], balance_cents: int, coupon_code: Optional[str]) -> int: """Policy B: With 2+ Large pizzas, every topping in the order gets $0.75 (50%) off.""" large_count = 0 total_toppings = 0 for pizza in pizzas: if pizza.size == "Large": large_count += 1 # Count toppings on every pizza in the order, including pizzas discounted by Policy A. total_toppings += len(pizza.toppings) if large_count < 2: return 0 return TOPPING_DISCOUNT_CENTS * total_toppings def policy_c_tier_percentage(pizzas: List[Pizza], balance_cents: int, coupon_code: Optional[str]) -> int: """Policy C: If remaining balance after A and B is at least $50.00, deduct 10%.""" # Use strict `<` so a balance of exactly 5000 cents ($50.00) still qualifies. if balance_cents < TIER_THRESHOLD_CENTS: return 0 # Compute 10% of balance_cents rounded to the nearest cent with half-cents (0.5) rounded up: # adding 5 before integer division by 10 turns e.g. 5375 (537.5 cents) into 5380 // 10 == 538. return (balance_cents + 5) // 10 def policy_d_fixed_coupon(pizzas: List[Pizza], balance_cents: int, coupon_code: Optional[str]) -> int: """Policy D: Exact coupon code 'SAVE5' deducts $5.00 (500 cents).""" if coupon_code == VALID_COUPON_CODE: return COUPON_DISCOUNT_CENTS return 0- Policy A (
Run the sequential pipeline with clamping in `Order`
Order.calculate_receipt()walksPOLICIESfrom"A"to"D", clamping each raw discount viaapplied_cents = min(raw_discount_cents, balance_cents)and recording only strictly positive deductions without mutatingself.pizzas:from typing import Dict, List, Optional POLICIES = [ ("A", policy_a_free_pizzas), ("B", policy_b_topping_special), ("C", policy_c_tier_percentage), ("D", policy_d_fixed_coupon), ] class Order: def __init__(self, coupon_code: Optional[str] = None): self.coupon_code = coupon_code # self.pizzas: list of Pizza objects in insertion order; never mutated during pricing. self.pizzas: List[Pizza] = [] def add_pizza(self, pizza: Pizza) -> None: self.pizzas.append(pizza) def calculate_receipt(self) -> Dict: # Phase 1: Sum all original pizza prices in integer cents. subtotal_cents = 0 for pizza in self.pizzas: subtotal_cents += pizza.price_cents() # Phase 2: Walk policies A -> B -> C -> D against a running balance in cents. balance_cents = subtotal_cents # discounts: list of {"policy": "A", "amount": 9.5} dicts for strictly positive deductions. discounts = [] for policy_name, policy_fn in POLICIES: raw_discount_cents = policy_fn(self.pizzas, balance_cents, self.coupon_code) # Clamp against balance_cents inside the loop so no intermediate or final balance drops below 0. applied_cents = min(raw_discount_cents, balance_cents) # Only record policies that actually reduced the balance by more than $0.00. if applied_cents > 0: balance_cents -= applied_cents discounts.append({ "policy": policy_name, "amount": cents_to_dollars(applied_cents), }) # Phase 3: Convert integer cents to dollar floats once at the boundary so lines sum to total. return { "subtotal": cents_to_dollars(subtotal_cents), "discounts": discounts, "total": cents_to_dollars(balance_cents), }Trace Example 1 and Example 2 step by step
First, trace Example 1 (
Large+ 4 toppings,Large+ 2 toppings,Small+ 1 topping, coupon"SAVE5"):Pizza prices: 1600 + 600 = 2200c, 1600 + 300 = 1900c, 800 + 150 = 950c Subtotal: 2200 + 1900 + 950 = 5050c ($50.50) Policy A: 3 // 3 = 1 free pizza -> lowest price is 950c ($9.50) balance_cents = 5050 - 950 = 4100c ($41.00) Policy B: 2 Large pizzas (>= 2), 7 total toppings * 75c = 525c ($5.25) balance_cents = 4100 - 525 = 3575c ($35.75) Policy C: balance_cents = 3575 < 5000 -> 0c (omitted even though subtotal was $50.50!) Policy D: coupon "SAVE5" -> min(500, 3575) = 500c ($5.00) balance_cents = 3575 - 500 = 3075c ($30.75) Receipt: subtotal = 50.5, discounts = [A: 9.5, B: 5.25, D: 5.0], total = 30.75 Check: 50.50 - (9.50 + 5.25 + 5.00) = 30.75Second, trace Example 2 (
Large+ 6 toppings,Large+ 5 toppings,Medium+ 2 toppings,Small+ 0 toppings, no coupon):Pizza prices: 2500c, 2350c, 1500c, 800c Subtotal: 2500 + 2350 + 1500 + 800 = 7150c ($71.50) Policy A: 4 // 3 = 1 free pizza -> lowest price is 800c ($8.00) balance_cents = 7150 - 800 = 6350c ($63.50) Policy B: 2 Large pizzas, 13 toppings * 75c = 975c ($9.75) balance_cents = 6350 - 975 = 5375c ($53.75) Policy C: 5375 >= 5000 -> (5375 + 5) // 10 = 538c ($5.38, rounding $5.375 half-up) balance_cents = 5375 - 538 = 4837c ($48.37) Policy D: coupon_code is None -> 0c (omitted) Check: 71.50 - (8.00 + 9.75 + 5.38) = 48.37 (exact to the penny!)Complete solution
from typing import Dict, List, Optional # Store all monetary constants as exact integer cents so binary floating-point # inaccuracies (like 0.1 + 0.2 == 0.30000000000000004) never cause 1-cent drift. # SIZE_PRICE_CENTS: maps size name -> base pizza price in cents (e.g., "Small" -> 800). SIZE_PRICE_CENTS = { "Small": 800, "Medium": 1200, "Large": 1600, } TOPPING_PRICE_CENTS = 150 TOPPING_DISCOUNT_CENTS = 75 TIER_THRESHOLD_CENTS = 5000 VALID_COUPON_CODE = "SAVE5" COUPON_DISCOUNT_CENTS = 500 def cents_to_dollars(cents: int) -> float: """Convert an exact integer cent amount into a two-decimal dollar float.""" return round(cents / 100, 2) class Pizza: def __init__(self, size: str, toppings: List[str]): if size not in SIZE_PRICE_CENTS: raise ValueError(f"Unknown pizza size: {size!r}") self.size = size # Copy the caller's list so mutating the original list later cannot alter this pizza's price. self.toppings = list(toppings) def price_cents(self) -> int: """Exact pizza price in integer cents: base size price + 150 cents per topping.""" base_cents = SIZE_PRICE_CENTS[self.size] toppings_cents = TOPPING_PRICE_CENTS * len(self.toppings) return base_cents + toppings_cents def get_price(self) -> float: return cents_to_dollars(self.price_cents()) # Every discount policy function shares one uniform signature: # (pizzas, balance_cents, coupon_code) -> raw_discount_cents # Keeping each rule in its own function isolates the policy math from balance clamping. def policy_a_free_pizzas(pizzas: List[Pizza], balance_cents: int, coupon_code: Optional[str]) -> int: """Policy A: Across every 3 pizzas in the order, the lowest-priced pizza overall is free.""" # price_cents_list: ascending list of individual pizza prices in cents, e.g., [950, 1900, 2200]. price_cents_list = [] for pizza in pizzas: price_cents_list.append(pizza.price_cents()) price_cents_list.sort() # Integer division drops leftover pizzas (< 3). free_count = len(price_cents_list) // 3 free_total_cents = 0 for i in range(free_count): free_total_cents += price_cents_list[i] return free_total_cents def policy_b_topping_special(pizzas: List[Pizza], balance_cents: int, coupon_code: Optional[str]) -> int: """Policy B: With 2+ Large pizzas, every topping in the order gets $0.75 (50%) off.""" large_count = 0 total_toppings = 0 for pizza in pizzas: if pizza.size == "Large": large_count += 1 # Count toppings on every pizza in the order, including pizzas discounted by Policy A. total_toppings += len(pizza.toppings) if large_count < 2: return 0 return TOPPING_DISCOUNT_CENTS * total_toppings def policy_c_tier_percentage(pizzas: List[Pizza], balance_cents: int, coupon_code: Optional[str]) -> int: """Policy C: If remaining balance after A and B is at least $50.00, deduct 10%.""" # Use strict `<` so a balance of exactly 5000 cents ($50.00) still qualifies. if balance_cents < TIER_THRESHOLD_CENTS: return 0 # Compute 10% of balance_cents rounded to the nearest cent with half-cents (0.5) rounded up: # adding 5 before integer division by 10 turns e.g. 5375 (537.5 cents) into 5380 // 10 == 538. return (balance_cents + 5) // 10 def policy_d_fixed_coupon(pizzas: List[Pizza], balance_cents: int, coupon_code: Optional[str]) -> int: """Policy D: Exact coupon code 'SAVE5' deducts $5.00 (500 cents).""" if coupon_code == VALID_COUPON_CODE: return COUPON_DISCOUNT_CENTS return 0 # POLICIES: ordered pipeline of (policy_label, policy_fn) evaluated strictly from A to D. POLICIES = [ ("A", policy_a_free_pizzas), ("B", policy_b_topping_special), ("C", policy_c_tier_percentage), ("D", policy_d_fixed_coupon), ] class Order: def __init__(self, coupon_code: Optional[str] = None): self.coupon_code = coupon_code # self.pizzas: list of Pizza objects in insertion order; never mutated during pricing. self.pizzas: List[Pizza] = [] def add_pizza(self, pizza: Pizza) -> None: self.pizzas.append(pizza) def calculate_receipt(self) -> Dict: # Phase 1: Sum all original pizza prices in integer cents. subtotal_cents = 0 for pizza in self.pizzas: subtotal_cents += pizza.price_cents() # Phase 2: Walk policies A -> B -> C -> D against a running balance in cents. balance_cents = subtotal_cents # discounts: list of {"policy": "A", "amount": 9.5} dicts for strictly positive deductions. discounts = [] for policy_name, policy_fn in POLICIES: raw_discount_cents = policy_fn(self.pizzas, balance_cents, self.coupon_code) # Clamp against balance_cents inside the loop so no intermediate or final balance drops below 0. applied_cents = min(raw_discount_cents, balance_cents) # Only record policies that actually reduced the balance by more than $0.00. if applied_cents > 0: balance_cents -= applied_cents discounts.append({ "policy": policy_name, "amount": cents_to_dollars(applied_cents), }) # Phase 3: Convert integer cents to dollar floats once at the boundary so lines sum to total. return { "subtotal": cents_to_dollars(subtotal_cents), "discounts": discounts, "total": cents_to_dollars(balance_cents), }✅ Submit now — all tests should pass.
Intuition & how it works
Picture a checkout register that scans all items in your cart once to establish the starting bill, then walks down a fixed four-step promotion checklist (A -> B -> C -> D). Each promotion inspects the basket and the current unpaid balance, proposes a deduction, and the register subtracts min(proposed, balance)—never allowing the unpaid balance to dip below $0.00—before advancing to the next promotion.
Implementing this directly with binary floating-point numbers (float, which stores base-2 approximations of decimal fractions) inside one big if/else method introduces two classic bugs. First, float multiplication and round(..., 2) treat half-cents inconsistently (round(51.25 * 0.10, 2) yields 5.12, while round(53.75 * 0.10, 2) yields 5.38), and accumulated rounding error can make subtotal - sum(discounts) miss total by $0.01. Second, tangling all four promotions inside calculate_receipt() makes it easy to accidentally test Policy C against the original subtotal instead of the post-A/B running balance.
Computing everything in integer cents ($1.00 = 100 cents) and isolating each rule into a uniform function eliminates both problems. Walk through Example 1 (Large + 4 toppings = 2200c, Large + 2 toppings = 1900c, Small + 1 topping = 950c, coupon "SAVE5"):
1. Subtotal starts at 2200 + 1900 + 950 = 5050 cents ($50.50).
2. Policy A sorts [950, 1900, 2200], sees 3 // 3 = 1 free item, and deducts 950c -> running balance becomes 4100c.
3. Policy B sees 2 Large pizzas and 7 total toppings, deducting 7 * 75 = 525c -> running balance becomes 3575c.
4. Policy C checks 3575 >= 5000, sees it is false (even though subtotal was 5050c), and deducts 0c (omitted).
5. Policy D matches "SAVE5" and deducts 500c -> final total is 3075c ($30.75).
Complexity
- Time:
Pizza.__init__runs inO(t)time forttoppings on that pizza because it makes a shallow copy oftoppings.Pizza.get_price()runs inO(1)time.Order.add_pizzaruns in amortizedO(1)time (occasional list growth averages out to constant cost per append).Order.calculate_receiptruns inO(n log n)time fornpizzas: summing the subtotal isO(n), Policy A sortsninteger prices inO(n log n), Policy B scans thenpizzas inO(n), and Policies C and D each run inO(1). Withn <= 100,O(n log n)finishes in microseconds.
- Space:
calculate_receiptallocatesO(n)auxiliary memory forprice_cents_listin Policy A, plusO(1)space for"discounts"(at most4dictionaries).
Edge cases
- Empty order with
"SAVE5":subtotal_cents = 0; Policy D's500c deduction is clamped viamin(500, 0)to0c, producing"discounts": []and"total": 0.0. - Fewer than 3 pizzas or remainder items: Integer division
n // 3yields0free pizzas for1or2items and1free pizza for4or5items. - Running balance of exactly
$50.00: Policy C checksbalance_cents < 5000, so5000c ($50.00) qualifies for the$5.00(10%) tier deduction. - Initial subtotal >=
$50.00, post-A/B balance <$50.00: As in Example 1 ($50.50dropping to$35.75), Policy C evaluates the post-A/B balance and skips the10%deduction. - Half-cent rounding on Policy C: Whenever
balance_centsends in5(such as5375c =$53.75in Example 2),10%is537.5cents ($5.375). Integer arithmetic(balance_cents + 5) // 10rounds half-cents up to538c ($5.38) and subtracts that exact cent amount so the receipt reconciles to the penny. - Ties among cheapest pizzas: Because Policy A sums the
n // 3smallest prices and Policy B counts toppings across the entire order regardless of which pizza was free, price ties never change any discount line. - Repeated
calculate_receipt()calls: Pricing never mutatesself.pizzas, so recomputing receipts before and after adding more pizzas always stays accurate.
Common mistakes
- Doing arithmetic in
floatthroughout: Subtracting rounded floats step by step can introduce binary representation drift wheresubtotal - sum(discounts)differs fromtotalby$0.01. - Testing Policy C against the pre-discount subtotal rather than the balance remaining after Policies A and B.
- Grouping pizzas in insertion chunks of 3 for Policy A: Ordering
6pizzas makes the2lowest-priced pizzas across all6items free, not the cheapest of items1..3plus the cheapest of items4..6. - Emitting
$0.00entries in"discounts": Any promotion whose clamped deduction equals0must be excluded from"discounts". - Mutating
self.pizzaswhile computing Policy A: Sorting or poppingself.pizzasdirectly corrupts subsequentcalculate_receipt()calls.
Follow-up questions
-
How could you apply Strategy or Chain of Responsibility so promotional rule order can be reconfigured from external data without code changes? Under the Strategy pattern (encapsulating each interchangeable rule inside its own object behind a shared interface), define a
DiscountPolicyprotocol withcompute_cents(order_ctx) -> intand register concrete strategies in a lookup tablePOLICY_REGISTRY = {"A": FreeThirdPizzaPolicy(), "B": HalfPriceToppingPolicy(), ...}. Loading an ordered rule list such as["B", "A", "C", "D"]from a database row or JSON config lets operators reorder or toggle promotions at runtime without redeploying code. When rules also need short-circuiting (for instance, an exclusive promo code that halts downstream discounts), the Chain of Responsibility pattern (where each handler updates the context and decides whether to invoke the next handler or stop) adds ahalt_pipeline: boolflag cleanly. -
How would you track item-level discount state if toppings on a free Policy A pizza were excluded from Policy B's half-off promotion? Create per-calculation
LineItem(pizza, original_idx, is_free=False)wrappers insidecalculate_receipt. Sort those wrappers by(pizza.price_cents(), original_idx)—usingoriginal_idxfor deterministic tie-breaking (note that distinct pizza sizes here cannot even tie in price because$4.00and$8.00base-price gaps are not multiples of$1.50, so tied pizzas always have identical topping counts)—and setis_free = Trueon the firstn // 3wrappers. Policy B then checks the2+Large condition and sumslen(item.pizza.toppings)exclusively across wrappers withnot item.is_free. If downstream tax or partial-refund logic also needs basket-wide discounts C and D split across paid items, allocate cents proportionally via the largest-remainder method (flooring each item's fractional share and distributing leftover pennies to the items with the largest fractional remainders). -
Why does representing money in integer cents eliminate binary floating-point drift, and how should fractional-cent percentage discounts be rounded? IEEE-754 binary floats cannot represent decimal fractions like
0.10or0.01exactly in base 2, so repeated additions and multiplications accumulate tiny representation errors that flip rounding boundaries unpredictably. Storing every price, balance, and deduction as an exactintcount of cents makes addition, subtraction, and whole-cent multiplication 100% exact, confining rounding to explicit percentage divisions like Policy C's10%. At those percentage steps, enforce one explicit rule—such as round half up ((balance_cents + 5) // 10) or banker's rounding / round half to even (rounding exact.5ties to the nearest even cent to eliminate systematic upward bias across millions of transactions)—and subtract that exact integer cent deduction frombalance_centsso line items and totals always sum identically.
Alternative approaches
- Base-10
decimal.Decimalarithmetic: Representing prices asDecimal("16.00")andDecimal("1.50")withquantize(Decimal("0.01"), rounding=ROUND_HALF_UP)avoids binary float issues directly in decimal dollars, trading slightly heavier object overhead for explicit accounting rounding modes. - Heap selection (
heapq.nsmallest) for Policy A: Finding thek = n // 3smallest prices via a min-heap runs inO(n log k)(orO(n)average via quickselect, a partial-partitioning algorithm), which only matters if basket sizes grow far beyondn <= 100.
Follow-up questions
- How could you apply Strategy or Chain of Responsibility so promotional rule order can be reconfigured from external data without code changes?
- How would you track item-level discount state if toppings on a free Policy A pizza were excluded from Policy B's half-off promotion?
- Why does representing money in integer cents eliminate binary floating-point drift, and how should fractional-cent percentage discounts be rounded?
Similar questions
- Fix and Extend a Nested Price Tracker
- Maximum Point Coverage by a Bounded-Perimeter Rectangle
- Internal Corporate Knowledge Retrieval and Agent Platform
- Equalizing Nine Stones Across a 3x3 Grid
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target