Breaking a problem down
How to go from a vague request to working code: understand the problem, list examples and edge cases, split it into small functions, build and test each piece, then put them together. One worked example, start to finish.
The first eight parts of this series were about the pieces: types, memory, scope, conditions, loops, functions, and data structures. This part is about the skill that ties them together. Most real tasks don’t arrive as “write a loop”. They arrive as “can you make me a monthly sales report?”, and the hard part is turning that into code.
In part 0 we met two ideas for this: Pólya’s four steps (understand, plan, carry out, look back) and Jeannette Wing’s description of computational thinking as “using abstraction and decomposition when attacking a large complex task”. This part puts them to work on one example, from the first question to the finished code.
The task
“Every month I need to know how much we sold per product. The orders are in a CSV export.”
The export looks like this:
date,product,qty,price,status
2026-10-03,book,2,85000,paid
2026-10-05,pen,10,4000,paid
2026-10-05,book,1,85000,cancelled
2026-10-12,mug,3,35000,paid
2026-11-01,book,1,85000,paid
2026-10-20,pen,5,4000,paid
2026-10-21,mug,abc,35000,paid
The temptation is to open an editor and start typing. Resist it for a few minutes.
Step 1: understand the problem
Write down, in plain words, what goes in and what comes out.
- Input: a CSV file and a month, like
2026-10. - Output: revenue per product for that month, plus a total.
Then ask the questions the request didn’t answer. Each one is a bug avoided:
- Do cancelled orders count? (Here: no, only
paid.) - Revenue is qty × price, not just price?
- What about a row with bad data, like
qty = abc? Crash, or skip and report it? - What if a month has no orders? An empty report, or an error?
- Sorted how? (Here: biggest revenue first.)
It also helps to work out one answer by hand. For October: books 2 × 85,000 = 170,000 (the cancelled one doesn’t count), mugs 3 × 35,000 = 105,000 (the abc row is skipped), pens 10 × 4,000 + 5 × 4,000 = 60,000. Total 335,000. Now you have something to check the code against.
Step 2: break it into steps
Write the steps as sentences before writing any code. A good test for each step: can you describe it in one short sentence, without “and”?
- Read the rows from the CSV file.
- Turn each row into a clean order, or reject it if the data is bad.
- Keep only paid orders in the requested month.
- Add up revenue per product.
- Format the result as a readable report.
That’s decomposition. Each step is small enough to write and test on its own, and each one becomes a function. This is the top-down approach: it “starts with the big picture, then breaks down into smaller segments.”
Step 3: write the top level first (“wishful thinking”)
A useful trick is to write the main function as if the smaller functions already existed. Structure and Interpretation of Computer Programs starts its rational-number example this way, “assuming that we already have a way of constructing a rational number”, and names the trick: “We are using here a powerful strategy of synthesis: wishful thinking.”
def monthly_report(path, month):
rows = read_orders(path)
orders = [o for o in (parse_order(r) for r in rows) if o is not None]
skipped = len(rows) - len(orders)
report = format_report(month, revenue_by_product(paid_in_month(orders, month)))
return report + (f"\n ({skipped} invalid row skipped)" if skipped else "")
None of those helpers exist yet, but the plan is now code, and it reads almost like the list from step 2. If this top level looks wrong, it’s much cheaper to change now than after writing everything underneath.
Step 4: build each piece, and check it alone
Now fill in the pieces one at a time, and try each one before moving on.
import csv
from collections import defaultdict
def read_orders(path):
with open(path, newline="") as f:
return list(csv.DictReader(f))
def parse_order(row):
"""Return a clean order dict, or None if the row is invalid."""
try:
return {
"month": row["date"][:7],
"product": row["product"],
"qty": int(row["qty"]),
"price": int(row["price"]),
"status": row["status"],
}
except (ValueError, KeyError):
return None
Check it with one good row and one bad row:
{'month': '2026-10', 'product': 'book', 'qty': 2, 'price': 85000, 'status': 'paid'}
None
Next pieces:
def paid_in_month(orders, month):
return [o for o in orders if o["month"] == month and o["status"] == "paid"]
def revenue_by_product(orders):
totals = defaultdict(int)
for o in orders:
totals[o["product"]] += o["qty"] * o["price"]
return dict(totals)
revenue_by_product on two pen orders gives {'pen': 60000}, which matches the hand calculation. Notice that these are pure functions from part 7: no files, no printing, so checking them takes one line. The only function that touches the outside world is read_orders.
def format_report(month, totals):
lines = [f"Sales {month}"]
for product, amount in sorted(totals.items(), key=lambda kv: kv[1], reverse=True):
lines.append(f" {product:<6} Rp{amount:>10,}")
lines.append(f" {'total':<6} Rp{sum(totals.values()):>10,}")
return "\n".join(lines)
Step 5: put it together and look back
Running monthly_report("orders.csv", "2026-10"):
Sales 2026-10
book Rp 170,000
mug Rp 105,000
pen Rp 60,000
total Rp 335,000
(1 invalid row skipped)
Same numbers as the hand calculation. And the edge case of a month with no orders:
Sales 2026-12
total Rp 0
Pólya’s last step, “Look back”, is where you ask: is it correct, is it clear, what would break it? Some honest answers here:
- Amounts are stored as whole rupiah, not floats, so the rounding problems from part 2 don’t apply.
- Skipping bad rows silently could hide a real data problem, so the report says how many were skipped.
- If the export grows to millions of rows, reading everything into a list will need rethinking. That’s a later problem, and it only touches
read_orders.
The same plan in another language
The decomposition doesn’t depend on Python. Here are two of the same pieces in PHP:
function paidInMonth(array $orders, string $month): array {
return array_filter($orders, fn($o) => $o['month'] === $month && $o['status'] === 'paid');
}
function revenueByProduct(array $orders): array {
$totals = [];
foreach ($orders as $o) {
$totals[$o['product']] = ($totals[$o['product']] ?? 0) + $o['qty'] * $o['price'];
}
return $totals;
}
// two pen orders → {"pen":60000}
Once the steps are clear, translating them is the easy part.
Techniques worth keeping
- Write the steps in plain sentences first. If you can’t write the step, you can’t write the code.
- Work one example by hand. It gives you a target to check against and often reveals questions you hadn’t asked.
- One job per function. The old Unix advice still holds: “Write programs that do one thing and do it well.”
- Top-down, then fill in. Write the main function with wishful thinking, then build the helpers.
- Solve a smaller version first. One month before a date range, one file before a folder, one user before all users.
- Explain it out loud. Rubber duck debugging, named after “an anecdote told in The Pragmatic Programmer”, is explaining your code “step by step, in natural language”. Saying the plan out loud works before the code exists, too.
- Divide and conquer is the same idea as an algorithm design technique: break a problem “into two or more sub-problems of the same or related type, until these become simple enough to be solved directly.”
Why this matters day to day
- Estimates. Small steps are much easier to estimate than “build the report”.
- Fewer surprises. The questions in step 1 (cancelled orders, bad rows, empty months) are exactly the ones that otherwise show up as bug reports.
- Easier changes. When the client asks for “per category instead of per product”, only
revenue_by_productand the formatting change. - Working with AI tools. A prompt like “write
paid_in_month(orders, month)that keeps only paid orders in that month” gets far better results than “make me a sales report”, because you’ve already done the thinking.
Try it yourself
- Add a feature: the report should also show the number of orders per product. Which functions change, and which don’t?
- Change the input to a date range instead of a month. Write the new steps as sentences before touching the code.
- Take a task from your own work and write its steps as five sentences, each without the word “and”.
- Explain the
monthly_reportfunction out loud, line by line, to an imaginary colleague (or a rubber duck).
Summary
- Don’t start with code. Start with input, output, and questions about the unclear parts.
- Work one example by hand to have something to check against.
- Decompose into steps you can describe in one sentence each; each step becomes a function.
- Write the top level first with wishful thinking, then build and test each piece on its own.
- Look back: check the result, the edge cases, and what would break it.
- The plan is language-independent; once it’s clear, the code is the easy part.
References
- Harold Abelson and Gerald Jay Sussman, Structure and Interpretation of Computer Programs, section 2.1.1, MIT Press.
- George Pólya, How to Solve It, Princeton University Press, 1945. Summary: How to Solve It.
- Jeannette M. Wing, Computational Thinking, Communications of the ACM 49(3), March 2006.
- Bottom-up and top-down approaches, Unix philosophy, Rubber duck debugging, and Divide-and-conquer algorithm, Wikipedia.