🎯 Python Decision Science — When Greedy Fails 🐍
Posted on: December 2, 2026
Description:
You have ten hours on one workbench and three orders to choose from. Each customer pays the agreed contribution only for a finished order. Which booking do you accept first?
| Order | Hours | Contribution | Credits per hour |
|---|---|---|---|
| Sign | 6 | 66 | 11 |
| Shelf | 5 | 50 | 10 |
| Frame | 5 | 45 | 9 |
Each order is available once. There are no setup costs, partial payments, or earnings for unused hours. The objective is total contribution in a single shift.
Follow the greedy decision
Rank the orders by credits per hour, accept the first one that fits, and continue down the ranking. The sign looks attractive at 11 credits per hour. It takes six hours, leaving four. Both remaining orders need five hours, so the workshop finishes with 66 credits.
The problem is what the ranking leaves out. The sign’s rate describes the six hours spent making it. It assigns no cost to the four hours left over. Across the whole shift, that booking earns 6.6 credits per available hour.
Replay the first choice
Pass on the sign and book the shelf and frame. They fit exactly: 5 + 5 hours, for 50 + 45 = 95 credits. That is a 29-credit gap under the same constraint.
Python can verify whether another combination does even better. The notebook uses itertools.combinations to generate every subset, including the empty schedule.
def best_plan(orders, capacity):
feasible = (p for p in subsets(orders) if hours(p) <= capacity)
return max(feasible, key=credits)
Three yes-or-no decisions give eight subsets. Five fit: no jobs, any of the three single jobs, or the shelf and frame together. Their scores are 0, 66, 50, 45, and 95. The highest feasible score proves the optimum for this shift.
Change one constraint
| Shift | Greedy booking | Best booking | Credits forgone |
|---|---|---|---|
| 10 hours | Sign · 66 | Shelf + frame · 95 | 29 |
| 11 hours | Sign + shelf · 116 | Sign + shelf · 116 | 0 |
One extra hour lets a five-hour shelf fit beside the six-hour sign. Every rate is identical across the two runs. The set of feasible combinations changes.
This is a 0/1 knapsack decision: each item is taken whole or skipped. If partial orders earned proportional credit, the ten-hour shop could take the sign and four-fifths of a shelf for 106 credits, but that would be a different contract. For three orders, checking all subsets is cheap. For many orders, consider an exact method such as dynamic programming when the hour budget is an integer of manageable size.
No comments yet. Be the first to comment!