Skip to main content

Programming fundamentals · Beginner · 17 min

Break a programming problem into smaller steps

By Padding · Updated 18 Nov 2026
Python 3.15.2 · python:3.15-slim (Debian)

You will take a problem that feels too big, splitting a group's shared trip costs with few transfers, break it into four small functions you build and check one at a time, and keep a checklist for starting any problem.

On this page

Some problems look like one solid block. You read the task, you open an empty file, and nothing comes. That is not a sign you cannot program. It is a sign the problem is still too big to write down in one go. Experienced programmers rarely solve a big problem directly. They cut it into pieces small enough that each one is obvious, build the smallest piece, check it, and move on.

In this tutorial you practise that on one concrete problem: four friends went on a trip, different people paid for different things, and now they want to settle up so everyone has paid the same, with as few money transfers as possible. You restate the problem, work a small example by hand, split it into four sub-problems, and turn each one into a Python function that you check before writing the next. You finish with a working cost-splitter and a short checklist you can reuse on any problem.

Amounts in the examples are plain numbers. Read them as naira, cedis, shillings, rand, pounds or whatever your group uses; the code does not care. If you split costs over mobile money, each transfer can carry a fee, which is one practical reason to want fewer of them.

The commands use python3. On Windows outside WSL, type py instead. On an Android phone, the Termux app can install Python with pkg install python, and everything here runs offline.

Step 1 · Restate the problem in your own words

Before any code, write the problem down as a short statement with its inputs and outputs. Make a folder for this tutorial and save the statement in a file, so you can look back at it later:

Bash
mkdir -p ~/split-demo
cd ~/split-demo
cat > problem.txt <<'TXT'
Problem: after a trip, tell each person who to pay and how much,
so that everyone ends up having paid the same share.

Inputs:
- the people on the trip (some may have paid nothing)
- each expense: who paid it and how much

Output:
- a list of transfers, one per line: "<who> pays <whom> <amount>"

Rules:
- every expense is shared equally by everyone on the trip
- amounts have at most two decimal places
- use few transfers: never more than the number of people minus one
TXT
cat problem.txt

Writing the inputs and outputs forces decisions the original wording left open. "Shared equally by everyone" settles who pays for what. "At most two decimal places" tells you how precise the amounts are.

The last rule is a deliberate change. The original problem said "the fewest transfers". Finding the true minimum for any group is a much harder problem than it sounds, and you do not need it: a simple method that never needs more transfers than the number of people minus one is good enough for a group of friends. Restating a problem is where you spot that kind of trap and choose a goal you can reach.

Check it worked

cat prints the statement. Read it as if you were someone else: could you start working from it without asking a question? If not, add the missing rule now.

Step 2 · Solve a small example by hand

Code that you cannot do by hand, you cannot check. Make up a small, realistic trip and work it out on paper first. Save the trip as two data files:

Bash
cd ~/split-demo
cat > people.txt <<'TXT'
Ada
Bayo
Chidi
Dee
TXT
cat > expenses.csv <<'CSV'
payer,amount,what
Ada,120.00,fuel
Bayo,80.00,food
Ada,40.00,snacks
Chidi,60.00,park tickets
CSV
cat expenses.csv

Now work it through, writing each stage down:

  1. Total spent: 120 + 80 + 40 + 60 = 300.00. Four people, so each person's fair share is 75.00.
  2. What each person paid: Ada 160.00, Bayo 80.00, Chidi 60.00, Dee 0.00.
  3. Each balance is what they paid minus their share: Ada +85.00, Bayo +5.00, Chidi −15.00, Dee −75.00. Positive means the group owes them; negative means they owe the group. The balances add up to zero, as they must.
  4. Pay off the biggest debt first, to the person owed most. Dee owes 75.00 and Ada is owed 85.00, so Dee pays Ada 75.00. Ada is now owed 10.00. Chidi owes 15.00: Chidi pays Ada 10.00, then Chidi pays Bayo the last 5.00.

That is three transfers for four people. Save this answer exactly as you want the program to print it:

Bash
cd ~/split-demo
cat > expected.txt <<'TXT'
Dee pays Ada 75.00
Chidi pays Ada 10.00
Chidi pays Bayo 5.00
TXT

Notice that working by hand already showed you the stages: totals, balances, matching, writing out. You have found the sub-problems without trying.

Check it worked

You have people.txt, expenses.csv and expected.txt in ~/split-demo (ls shows them), and your written balances add up to zero: 85 + 5 − 15 − 75 = 0. If yours do not, find the mistake now; it would be in the code too.

Step 3 · Split the problem into sub-problems

Turn the stages from your hand calculation into a tree. The whole problem sits at the top. Under it go the pieces, each one small enough that you can describe it in one sentence, with a clear input and output. If a piece is still too big, split it again.

A problem tree. The top box reads "Split shared trip costs fairly". Below it are four boxes, left to right: 1. Read the expenses (read_trip), 2. Work out balances (balances), 3. Match who owes (settle), 4. Print the transfers (report). Each has two smaller tasks under it, such as "Amounts to whole cents" and "Sort both lists".
Each branch becomes one function. The output of each is the input of the next.

Write the plan down as one line per function: its name, what goes in and what comes out.

Bash
cd ~/split-demo
cat > plan.txt <<'TXT'
read_trip(people file, expenses file) -> list of names, list of (payer, cents)
balances(names, expenses)             -> {name: cents}, positive = is owed
settle(balances)                      -> list of (from, to, cents)
report(transfers)                     -> list of lines to print
TXT
cat plan.txt

The plan makes one more decision: amounts are kept as whole cents (or kobo, pesewas, pence), not as decimals. Computers store numbers like 0.1 in binary and cannot hold them exactly, so adding decimal money can leave tiny errors such as 0.30000000000000004. Whole numbers never do that. You convert to cents once, on the way in, and back to a decimal once, on the way out.

Check it worked

Read the plan.txt lines from top to bottom. The output of each line is what the next line needs as input, and the last line produces what problem.txt asked for. If two lines do not connect, a sub-problem is missing.

Step 4 · Build the smallest piece first: read the expenses

Start with the first piece and nothing else. Create splitter.py with two functions: one turns an amount like 120.00 into cents, the other reads both files:

Bash
cd ~/split-demo
cat > splitter.py <<'PY'
import csv
from pathlib import Path


def to_cents(text):
    """Turn an amount like "120.50" into whole cents: 12050."""
    return round(float(text) * 100)


def read_trip(people_file, expenses_file):
    """Return (people, expenses). Each expense is a (payer, cents) pair."""
    lines = Path(people_file).read_text(encoding="utf-8").splitlines()
    people = [line.strip() for line in lines if line.strip()]

    expenses = []
    with open(expenses_file, newline="", encoding="utf-8") as f:
        for row in csv.DictReader(f):
            payer = row["payer"].strip()
            if payer not in people:
                raise ValueError(f"{payer} paid but is not in {people_file}")
            expenses.append((payer, to_cents(row["amount"])))
    return people, expenses
PY

Line by line:

  • to_cents multiplies by 100 and rounds. float("0.29") * 100 comes out as 28.999999999999996, and round brings it back to 29.
  • read_trip reads people.txt and keeps every non-empty line, without spaces at either end, so a blank line at the end of the file does no harm.
  • csv.DictReader reads the header row (payer,amount,what) and gives you each later row as a dictionary, so row["amount"] works even if someone reorders the columns.
  • A payer who is not in the people list is almost always a typing mistake, such as Adaa. The function stops with a clear message instead of quietly getting the sums wrong.

Now write a small script that calls the function and checks its result against what you know from the hand calculation:

Bash
cd ~/split-demo
cat > check_read.py <<'PY'
from pathlib import Path

from splitter import read_trip, to_cents

people, expenses = read_trip("people.txt", "expenses.csv")
print(people)
print(expenses)
assert to_cents("0.29") == 29
assert expenses == [("Ada", 12000), ("Bayo", 8000), ("Ada", 4000), ("Chidi", 6000)]

Path("typo.csv").write_text("payer,amount,what\nAdaa,10.00,typo\n", encoding="utf-8")
try:
    read_trip("people.txt", "typo.csv")
except ValueError as err:
    print("caught:", err)
else:
    raise AssertionError("typo.csv should have been rejected")

print("read_trip OK")
PY
python3 check_read.py

assert stops the script with an AssertionError if its condition is false, and does nothing if it is true. It turns "looks right to me" into a check that the computer repeats every time you run it. The else after try/except runs only when no error was raised, so if read_trip ever stopped rejecting the typo, the script would stop there instead of printing read_trip OK.

Check it worked

The output is the list of four names, the four (payer, cents) pairs such as ('Ada', 12000), then caught: Adaa paid but is not in people.txt, and finally read_trip OK. If you see an AssertionError instead, the line number in the message tells you which check failed.

Step 5 · Compute each person's balance

The second piece takes the people and expenses and returns each person's balance in cents. Add it to the end of splitter.py:

Bash
cd ~/split-demo
cat >> splitter.py <<'PY'


def balances(people, expenses):
    """Return {name: cents}. Positive: the group owes them. Negative: they owe."""
    total = sum(cents for _, cents in expenses)
    share, leftover = divmod(total, len(people))

    result = {}
    for i, name in enumerate(people):
        extra = 1 if i < leftover else 0
        result[name] = -(share + extra)

    for payer, cents in expenses:
        result[payer] += cents
    return result
PY
  • divmod(total, len(people)) divides and gives two whole numbers: the share and what is left over. 30000 cents among four people is 7500 each with 0 left over.
  • Sometimes the total does not divide evenly: 100.00 among three people is 33.33 each with one cent spare. The loop gives that spare cent to the first person in the list, so the shares still add up to exactly the total.
  • Everyone starts at minus their share, as if they had paid nothing. Then each expense is added back to the person who paid it.

Check it against your hand calculation and against the uneven case:

Bash
cd ~/split-demo
cat > check_balances.py <<'PY'
from splitter import balances, read_trip

people, expenses = read_trip("people.txt", "expenses.csv")
result = balances(people, expenses)
print(result)
assert result == {"Ada": 8500, "Bayo": 500, "Chidi": -1500, "Dee": -7500}
assert sum(result.values()) == 0

uneven = balances(["A", "B", "C"], [("A", 10000)])
print(uneven)
assert uneven == {"A": 6666, "B": -3333, "C": -3333}
assert sum(uneven.values()) == 0

print("balances OK")
PY
python3 check_balances.py

Check it worked

The first line is {'Ada': 8500, 'Bayo': 500, 'Chidi': -1500, 'Dee': -7500}: the same balances you wrote by hand, in cents. The second is {'A': 6666, 'B': -3333, 'C': -3333}, which still adds up to zero. The last line is balances OK.

Step 6 · Match people who owe with people who are owed

This is the piece that looked hardest at the start. With the balances in hand, it is the method you used on paper: sort the people who owe from largest to smallest, do the same for the people who are owed, and keep paying the smaller of the two amounts at the top of each list.

Two columns. On the left, people who owe: Dee owes 75.00, Chidi owes 15.00. On the right, people who are owed: Ada 85.00, Bayo 5.00. Three numbered arrows: 1, Dee pays Ada 75.00; 2, Chidi pays Ada 10.00; 3, Chidi pays Bayo 5.00.
Each transfer clears at least one person, so four people need at most three transfers.

Add settle to splitter.py:

Bash
cd ~/split-demo
cat >> splitter.py <<'PY'


def settle(balance):
    """Return a list of (from_name, to_name, cents) that clears every balance."""
    debtors = [[name, -cents] for name, cents in balance.items() if cents < 0]
    creditors = [[name, cents] for name, cents in balance.items() if cents > 0]
    debtors.sort(key=lambda item: item[1], reverse=True)
    creditors.sort(key=lambda item: item[1], reverse=True)

    transfers = []
    d = c = 0
    while d < len(debtors) and c < len(creditors):
        amount = min(debtors[d][1], creditors[c][1])
        transfers.append((debtors[d][0], creditors[c][0], amount))
        debtors[d][1] -= amount
        creditors[c][1] -= amount
        if debtors[d][1] == 0:
            d += 1
        if creditors[c][1] == 0:
            c += 1
    return transfers
PY
  • debtors holds [name, amount owed] pairs as positive numbers, and creditors holds [name, amount due]. They are small lists rather than tuples because the amounts go down as transfers happen.
  • sort(key=..., reverse=True) puts the largest amount first. key tells sort to compare the second item of each pair, the amount.
  • d and c point at the current top of each list. Each pass pays the smaller of the two amounts, so at least one person reaches zero, and that pointer moves on. That is why the number of transfers can never be more than the number of people minus one.

Check it with the balances from the last step, plus two cases at the edges: a group where nobody owes anything, and a property that must hold for any input, that applying the transfers leaves everyone at zero:

Bash
cd ~/split-demo
cat > check_settle.py <<'PY'
from splitter import settle

sample = {"Ada": 8500, "Bayo": 500, "Chidi": -1500, "Dee": -7500}
transfers = settle(sample)
for transfer in transfers:
    print(transfer)
assert transfers == [("Dee", "Ada", 7500), ("Chidi", "Ada", 1000), ("Chidi", "Bayo", 500)]

assert settle({"A": 0, "B": 0}) == []

left = dict(sample)
for giver, taker, cents in transfers:
    left[giver] += cents
    left[taker] -= cents
assert all(cents == 0 for cents in left.values())
assert len(transfers) <= len(sample) - 1

print("settle OK")
PY
python3 check_settle.py

Check it worked

The script prints three tuples, ('Dee', 'Ada', 7500), ('Chidi', 'Ada', 1000) and ('Chidi', 'Bayo', 500), the transfers you worked out by hand, then settle OK.

Step 7 · Print the transfers and compare with your hand answer

The last piece turns cents back into readable amounts and builds one line per transfer. Add it, then write the small program that joins all four pieces:

Bash
cd ~/split-demo
cat >> splitter.py <<'PY'


def money(cents):
    """Turn 7500 into "75.00"."""
    return f"{cents // 100}.{cents % 100:02d}"


def report(transfers):
    """Return the lines to print, one per transfer."""
    if not transfers:
        return ["Everyone is square. No transfers needed."]
    return [f"{giver} pays {taker} {money(cents)}" for giver, taker, cents in transfers]
PY
cat > split_trip.py <<'PY'
from splitter import balances, read_trip, report, settle

people, expenses = read_trip("people.txt", "expenses.csv")
for line in report(settle(balances(people, expenses))):
    print(line)
PY
python3 split_trip.py > actual.txt
cat actual.txt
diff expected.txt actual.txt
echo "matches the hand-worked answer"
  • money uses whole-number division: cents // 100 is the whole part and cents % 100 the remainder. :02d pads the remainder to two digits, so 500 becomes 5.00, not 5.0.
  • split_trip.py is four lines because the work lives in the functions. Read the call from the inside out: read the trip, compute balances, settle them, build the report.
  • diff compares the program's output with the answer you saved before writing any code. It prints nothing when the files are the same. If they differ, it prints the lines that do not match instead; ignore the echo line after it and look at those lines.

Now change the data and run it again. Dee paid for fuel on the way home:

Bash
cd ~/split-demo
echo "Dee,40.00,fuel home" >> expenses.csv
python3 split_trip.py

Check it worked

The first run prints the three lines from expected.txt, then matches the hand-worked answer. After the new expense, the total is 340.00 and each share 85.00, so the output becomes:

Text
Dee pays Ada 45.00
Chidi pays Ada 25.00
Bayo pays Ada 5.00

Bayo, who was owed money before, now owes a little. Work that one out by hand too: it is a good test of whether you trust the program.

Step 8 · Keep the checklist for your next problem

You used the same five moves throughout. Save them as a checklist next to your code, then print it:

Bash
cd ~/split-demo
cat > checklist.txt <<'TXT'
Starting a problem
1. Restate it: write the problem, its inputs, outputs and rules in your own words.
2. Find inputs and outputs: decide their exact shape (types, units, file format).
3. Solve a small example by hand and save the answer you expect.
4. Split it: one sub-problem per stage, each with one input and one output.
5. Build the smallest piece first, check it with asserts, then build the next.
TXT
cat checklist.txt

When a piece still feels too big at step 5, go back to step 4 and split that piece. When the program gives a different answer from your hand calculation, test each function on its own with the check scripts: the one whose check fails is where the bug is. The tutorial on finding a bug step by step goes further with that.

When you are done, delete the demo folder:

Bash
cd ~
rm -rf ~/split-demo

Check it worked

cat prints the five-line checklist. Copy it somewhere you keep notes. Then try it on a small problem of your own, such as "who should host the next meeting, so everyone hosts as evenly as possible", and stop after step 3. If you can write a hand-worked answer, you are ready to split it.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.