CodeBlanks Logo Icon CodeBlanks

Summary - Greedy

Print the greedy coin change solution in a mini task.

Summary - Greedy

Greedy is a simple approach that picks the local best each step and never backtracks. It is optimal on standard coin systems.

In this mini task you will print the greedy coin change solution; combine all steps.

Greedy is often preferred in practice because it is fast and simple; but it is not always optimal.

Practice Print greedy

Write greedy_print(coins, amount). Print the greedy coin count with print(). Output: 6.

Starter code

solution.py
def greedy_print(coins, amount):
    # Print greedy coin count

Sample solution

solution.py
def greedy_print(coins, amount):
    # Print greedy coin count
    coins.sort(reverse=True)
    count = 0
    for coin in coins:
        count += amount // coin
        amount = amount % coin
    print(count)
greedy_print([25, 10, 5, 1], 63)

Expected output

6

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Summary - Greedy: match the terms

Term Meaning
greedy Local best
coin Coin
amount Amount
optimum Best

2 Counter increment

Question
count ____ amount // coin
Answer
count += amount // coin

Explanation: += is right.

3 What is greedy's biggest risk?

  • Being too slow
  • Missing the global optimum Correct answer
  • Memory usage
  • Infinite loop

Explanation: Missing the global optimum.

All lessons in Intermediate