livepython.net

261. Python Program to Make a Vending Machine That Gives Change

HardPhase 3 · Challenge

There are a few parts here, and each one uses something you know: a dictionary, split(), join() and loops. Work out the change for 7 coins on paper first.

Overview

A vending machine must give the right change, and it should not empty its coin box by paying in small coins. Shops and ticket machines use the same idea every day.

Problem Statement

Chidi looks after a snack machine at a school. The machine sells these items:

CodeItemPrice
A1Water12
A2Juice25
B1Chips18
B2Cookies30
C1Sandwich47

The machine takes and gives coins worth 10, 5, 2 and 1. Read the item code, then the coins put in. Then print one of these:

  • The code is not in the table: print Unknown item <code>, then Take back your <paid> coins.
  • The coins add up to less than the price: print Not enough coins: <item> costs <price>, then Take back your <paid> coins.
  • Otherwise: print You get <item>, then the change.

The change is the coins put in minus the price. Pay it with the fewest coins you can. Print it like Change: 8 = 5 + 2 + 1: the change, then each coin from the biggest to the smallest, with one space on each side of every = and +. When the change is 0, print only Change: 0.

Examples

Example 1. Input:

A2
10 10 10 2

gives:

You get Juice
Change: 7 = 5 + 2

Why: the coins add up to 32, and juice costs 25, so the change is 7. One 5 and one 2 make 7 with only 2 coins.

Example 2. Input:

C1
10 10 10 10

gives:

Not enough coins: Sandwich costs 47
Take back your 40 coins

Why: 40 is less than 47, so the machine keeps the sandwich and gives all 40 coins back.

Input

Two lines:

  1. The item code, like A2. Codes use capital letters, so a2 is an unknown code.
  2. The coins put in, with one space between them. There is at least 1 coin, and each coin is 10, 5, 2 or 1.

Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Output

Two lines, as described above. The tests try 9 different inputs, also an exact payment, a change of 1, a large change, and a change of 6, where one 5 and one 1 beat three 2s.

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

Finish this chapter firstChapter 13 · Dictionaries
solution.py
# write your code here

EXPECTED OUTPUT

1You get Juice
2Change: 7 = 5 + 2

YOUR OUTPUT

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