AI-Assisted Coding Lab · Total a Shopping Cart

30:00left of 30:00

Total a Shopping Cart

The checkout page needs a cart total with two discount codes. The README has the rules, and cart.py has the shape of the code. Build it with the assistant: accept, edit, or reject each suggestion, and keep the tests green.

cart.py1 of 3

Files

cart.py

Python · Editable
from decimal import Decimal
CODES = {
"SAVE10": ("percent", Decimal("10")),
"TAKE5": ("flat", Decimal("5.00")),
}
def line_total(unit_price, quantity):
"""unit_price is a string such as "4.99". Returns a Decimal."""
return Decimal(unit_price) * quantity
def subtotal(lines):
"""lines is a list of (sku, unit_price, quantity) tuples."""
raise NotImplementedError
def apply_code(amount, code):
"""Returns the amount after the discount code. Unknown codes change nothing."""
if code not in CODES:
return amount
kind, value = CODES[code]
return amount
def to_cents(amount):
"""Rounds to whole cents, half up, the way the payment provider does."""
return amount
def cart_total(lines, code=None):
return to_cents(apply_code(subtotal(lines), code))

Test Output

No runs yet.

Assistant

Scripted
  1. Send the first prompt to start.

Next Prompt

Write subtotal.