Coupon Calculator
Frequency: Reported
Given a shopping cart and one coupon, return the cart's total price after applying the coupon.
Each cart item contains a price and category:
shopping_cart = [
{'price': 2.00, 'category': 'fruit'},
{'price': 20.00, 'category': 'toy'},
{'price': 5.00, 'category': 'clothing'},
{'price': 8.00, 'category': 'fruit'},
]A coupon applies to one category:
coupon = {
'category': 'fruit',
'percent_discount': 15,
'amount_discount': None,
'minimum_num_items_required': 2,
'minimum_amount_required': 10.00,
}Exactly one of percent_discount and amount_discount must be non-null; return -1 if both or neither are supplied. Each minimum may independently be null. If a minimum is null, it imposes no restriction. Apply the coupon only when the matching category satisfies every supplied minimum.
For the example above, the fruit subtotal is 10.00, so a 15% discount reduces it to 8.50. The full cart total is therefore 33.50.
The reported implementation caps a fixed-amount discount at the eligible category's subtotal, preventing a negative subtotal.
Follow-up: multiple coupons and categories
Each coupon now has a categories list:
coupons = [
{
'categories': ['clothing', 'toy'],
'percent_discount': None,
'amount_discount': 6,
'minimum_num_items_required': None,
'minimum_amount_required': None,
},
{
'categories': ['fruit'],
'percent_discount': 15,
'amount_discount': None,
'minimum_num_items_required': 2,
'minimum_amount_required': 10.00,
},
]- If a category appears in more than one coupon, return
-1. - For each coupon, find its eligible categories and use the largest discount obtainable from any one of them.
- Sum the selected discounts and subtract them from the cart total.
With the cart and coupons above, the reported expected result is 27.50: a 6.00 discount from the first coupon and a 1.50 fruit discount from the second.
Submitted Python answers and tests for both parts
The code is preserved as reported, including variable-name mistakes in the original test section, and is not presented as a verified reference solution.