livepython.net

253. Python Program to Apply Coupon Codes to a Shopping Cart

MediumPhase 2 · Practice

This one takes a few steps. You know everything it uses: a while loop, split(), a list with min() and if with elif.

Overview

Online shops let you type a coupon code at the checkout. Each code has its own rule, and the shop must check the rule before it gives a discount.

Problem Statement

Diego runs an online shop. A cart has one line per item, as <item> <price> <quantity>, like pen 1.20 10. After the items, there may be one coupon line, coupon <CODE>. The input ends with a line end.

The subtotal is the sum of price × quantity for every item. The shop has 3 coupons:

  • SAVE10: 10% off the subtotal.
  • FLAT50: 50 coins off, but only when the subtotal is 200 coins or more. If it is less, print FLAT50 needs 200 coins or more and give no discount.
  • FREEONE: one of the cheapest item is free. The discount is the lowest price in the cart.

For any other code, print Invalid coupon: <CODE> and give no discount. Codes must match exactly, so save10 is not valid. With no coupon line, there is no discount and no message.

After the message, if there is one, print these 3 lines, all with 2 decimal places:

Subtotal: <subtotal>
Discount: <discount>
Total: <total>

The total is the subtotal minus the discount.

Examples

Example 1. Input:

notebook 4.50 3
pen 1.20 10
bag 25 1
coupon SAVE10
end

gives:

Subtotal: 50.50
Discount: 5.05
Total: 45.45

Why: 4.50 × 3 = 13.50, 1.20 × 10 = 12.00 and 25 × 1 = 25, so the subtotal is 50.50. 10% of 50.50 is 5.05, and 50.50 - 5.05 = 45.45.

Example 2. Input:

shoes 120 1
socks 5 4
coupon FLAT50
end

gives:

FLAT50 needs 200 coins or more
Subtotal: 140.00
Discount: 0.00
Total: 140.00

Why: the subtotal is 120 + 20 = 140. That is less than 200, so FLAT50 gives no discount, and the message comes first.

Input

One item per line: a one-word item name, the price (a number above 0, maybe with a decimal point) and the quantity (a whole number of 1 or more), with one space between them. There is at least one item. Then at most one coupon line, coupon and a one-word code. The last line is always end. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Output

Three lines, or four when there is a message. The tests try 8 different inputs: every coupon, a subtotal of exactly 200, a code in small letters, an unknown code and a cart with no coupon.

Try it first. The solution opens when you solve this question, or after 3 tries with Submit.

Finish this chapter firstChapter 12 · Working With Strings
solution.py
# write your code here

EXPECTED OUTPUT

1Subtotal: 50.50
2Discount: 5.05
3Total: 45.45

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.