Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Implement an Order Composed of Line Items

Model an Order using composition: build LineItem objects and an Order that manages them and computes totals, taxes, and queries.

Python practice15 minComposition & Real-World ModelingIntermediateLast updated April 11, 2026

Problem statement

You will implement two classes: LineItem and Order. A LineItem represents a single product entry with a name, quantity, unit price, and whether it's taxable. An Order is composed of multiple LineItem instances and provides methods to manage items and compute order-level information. Specifically, implement: - LineItem(name: str, quantity: int, unit_price: float, taxable: bool = False) - Order(items: list[LineItem] | None = None) Order methods to implement: - add_item(item: LineItem) -> None : add a LineItem to the order - remove_item(name: str) -> bool : remove the first LineItem with the given name; return True if removed else False - total() -> float : return the sum of quantity * unit_price for all items - total_with_tax(tax_rate: float) -> float : apply tax_rate (e.g., 0.1 for 10%) only to taxable items and return total + tax - most_expensive_item_name() -> str | None : return the name of the item with the highest unit_price, or None if order is empty Write clean, idiomatic Python and make sure the methods behave sensibly for edge cases (empty order, removing non-existent items).

Task

Implement LineItem and Order classes to practice composition: adding/removing items, computing totals, tax application, and querying the most expensive item.

Examples

Simple total

Input

Order([LineItem('apple', 2, 1.0), LineItem('banana', 3, 0.5)]).total()

Output

3.5

apple: 2*1.0 = 2.0; banana: 3*0.5 = 1.5; total = 3.5

Tax applied only to taxable items

Input

Order([LineItem('book', 1, 10.0, taxable=False), LineItem('perfume', 2, 5.0, taxable=True)]).total_with_tax(0.1)

Output

21.0

Total before tax = 20.0. Only perfume is taxable: taxable amount = 10.0, tax = 1.0. Total with tax = 21.0

Input format

The harness will eval an expression that uses the classes you implement, for example: Order([...]).total()

Output format

Return values are compared by str(value). Ensure methods return simple Python types (float, str, None) so their string representations match expected outputs.

Constraints

- Do not use external libraries. - Keep numeric calculations precise by using simple fractions (0.5, 1.0) to avoid floating-point surprises in tests. - Methods should handle empty orders and attempts to remove missing items gracefully.

Samples

Sample 1

Input

Order([LineItem('pen', 5, 2.0), LineItem('pencil', 2, 1.0)]).remove_item('pen'); Order([LineItem('pen', 5, 2.0), LineItem('pencil', 2, 1.0)]).total()

Output

12.0

Sample shows typical usage; removing in one expression isn't necessary for samples. Start value: 5*2 + 2*1 = 12.0