Menu

Decomposition

Decomposition means breaking a problem, a solution or an algorithm down into smaller parts. Instead of facing one huge task, you work on several small ones that you can get your head around.

Each smaller part is called a sub-problem, also known as a subtask. It is still a job in its own right, just small enough to think about separately from the rest.

Breaking a problem down

Imagine you must write a program for a school book club that shows which member has read the most books. As one single task that is daunting, but decomposed it becomes:

  • store each member's name and how many books they have read
  • find the highest number of books read
  • print that number with the member's name beside it

Each of those is a sub-problem, and any of them can be broken down again. "Find the highest number" becomes: take the first count as the best so far, compare each remaining count in turn, and replace the best whenever you meet a bigger one. That step is now small enough to turn into code straight away.

When to stop

Decomposition does not have to carry on until every task is a single line of code. You stop when each remaining task is manageable — easy to work with and clearly understood. A block of twenty lines that does one clear job is perfectly manageable, so there is no need to split it further.

Decomposition is not only for problems, either. A finished solution and the algorithm behind it can be split up in the same way: a program that controls a school greenhouse's watering divides into reading the soil moisture, deciding whether watering is needed, and opening the valve for the right length of time, and each part can be written, tested and improved on its own.

The program below is a solution broken into small blocks: one works out the best count and another uses it to report the champion.

def findBest(counts):
    best = counts[0]
    for number in counts:
        if number > best:
            best = number
    return best

def showChampion(names, counts):
    best = findBest(counts)
    for i in range(len(counts)):
        if counts[i] == best:
            print(names[i] + " read " + str(best) + " books")

names = ["Aisha", "Ben", "Chi", "Dara", "Eve"]
counts = [4, 9, 6, 7, 2]
showChampion(names, counts)

Output:

Ben read 9 books

Practise this