Python 3D Academyবাংলা

The greedy choice, and when it fails

🌍 In real life. A shopkeeper in Dhaka gives you 1,386 taka in change with as few notes as possible. Without thinking, they reach for the biggest note that fits: a 1,000, then three 100s, a 50, a 20, a 10, a 5 and a 1. Nine notes, and nobody can do it with fewer. Now imagine a country whose coins are 1, 3 and 4, and the change is 6. The same habit gives 4 + 1 + 1, three coins, but 3 + 3 needs only two.

The idea in one sentence: a greedy algorithm builds its answer one step at a time, each time taking the choice that looks best right now and never going back; it is right only when that choice is always safe, and one counterexample is enough to show it isn't.

Its words:

  • greedy choice: the option that looks best at this step, judged on its own
  • safe choice: one that some best answer also makes, so taking it never closes the way to the best
  • counterexample: one input where the greedy answer is worse than the best

Making change greedily, step by step:

  1. sort the notes from biggest to smallest
  2. take the biggest note while it still fits in what is left
  3. move on to the next note, and stop when nothing is left

Whether greedy works depends on choosing the right rule. Here a tempting rule, "take the meeting that starts first", books one room for the day:

Why greedy is safe for taka, and not for 1, 3, 4. For the taka notes the shortcut always works, and you can check it case by case. For example, a best answer never holds two 1s (one 2 does the same), three 2s (a 5 and a 1), two 5s (a 10), or 20 + 20 + 10 (a 50). Going through every such case shows that, whatever is left, the biggest note that fits is in some best answer. With coins 1, 3 and 4, two 3s can't be swapped for anything smaller in number, and 6 = 3 + 3 never uses the 4 that greedy grabs first.

What it costs, by counting. Greedy looks at each kind of note once and subtracts: for 9 kinds of note and 1,386 taka, 9 notes chosen in about 18 steps. Trying every mix of notes instead grows explosively. When greedy isn't safe, a search that is sure to find the best (like the breadth-first search below, or Chapter 57's tables) costs more but is always right.

def greedy_notes(amount, notes):
    used = []
    for note in sorted(notes, reverse=True):     # the biggest note first
        while amount >= note:                    # take it as often as it fits
            used.append(note)
            amount -= note
    return used

print(greedy_notes(1386, [1, 2, 5, 10, 20, 50, 100, 500, 1000]))
print(greedy_notes(6, [1, 3, 4]))
from collections import deque

def fewest_coins(amount, coins):
    count = {0: 0}                      # amount made so far -> fewest coins to make it
    queue = deque([0])
    while queue:
        made = queue.popleft()
        if made == amount:
            return count[made]
        for c in coins:
            nxt = made + c
            if nxt <= amount and nxt not in count:
                count[nxt] = count[made] + 1
                queue.append(nxt)
    return -1

print(fewest_coins(6, [1, 3, 4]))

Mistakes and edge cases.

  • trusting greedy without a reason: it is tempting and fast; look for a counterexample, or an exchange argument like Lesson 55.4's, before relying on it
  • notes in the wrong order: greedy must try the biggest first; given in any order, sort them
  • an amount greedy can't finish: with coins 2 and 4, an odd amount is left over; greedy then returns a wrong answer unless you check that nothing is left
  • the right rule matters: earliest start fails for meetings, but earliest end is safe (Lesson 56.2)

Quiz

  1. What does a greedy algorithm do at each step?

    • Takes the choice that looks best right now, and never goes back
    • Tries every choice and keeps the best
    • Picks a choice at random
  2. What does this print?

    def greedy_notes(amount, notes):
        used = []
        for note in sorted(notes, reverse=True):     # the biggest note first
            while amount >= note:                    # take it as often as it fits
                used.append(note)
                amount -= note
        return used
    
    print(greedy_notes(6, [1, 3, 4]))
  3. With coins 1, 3 and 4, how few coins make 6?

    • 2, as 3 + 3
    • 3, as 4 + 1 + 1
    • 1
  4. How do you show that a greedy rule is wrong?

    • Find one input where its answer is worse than the best
    • Run it on many inputs and see it finish
    • Check that it is fast
  5. Given the notes in any order, this sometimes uses too many. Which line is wrong?

    def greedy_notes(amount, notes):
        used = []
        for note in notes:
            while amount >= note:
                used.append(note)
                amount -= note
        return used

Coding tasks

  1. Write greedy_notes(amount, notes): return the list of notes a greedy shopkeeper hands over, biggest first. The notes may be given in any order.

  2. When greedy isn't safe, search. Write fewest_coins(amount, coins): the fewest coins (each kind as often as you like) that make exactly amount, or -1 if it can't be made. Use breadth-first search (Chapter 51): each amount made so far is a vertex, and adding one coin is an edge.