Sub topic 4
Code in Sequence: Adding Costs
Most real functions are a series of separate pieces: some setup, a loop, maybe a second loop, then a return. This chapter shows how to combine the step counts of those pieces. If one block runs to completion before the next one starts, you add their costs.
The chapter assumes you can count the iterations of a single loop from its bounds and step size, as covered in the previous two chapters. It also assumes you can read Python for loops, if statements, and function calls.
The Addition Rule
Code blocks are in sequence when they sit at the same indentation level, one after another, so each block finishes before the next begins. If block A costs T_A steps and block B costs T_B steps, then running A followed by B costs:
T_total = T_A + T_B
This works because neither block changes how often the other runs. The second loop starts only after the first loop is done, and it runs the same number of times whether the first loop took one step or a million.
A Worked Example: Two Passes Over a List
The function below counts how many values are above the mean. It needs one pass to compute the total and a second pass to compare each value with the mean. The counter adds one step for each constant-time statement outside the loops and one step for each loop iteration.
def count_above_mean(data):
steps = 0
total = 0
steps += 1 # setup: 1 step
for x in data: # pass 1: n iterations
total += x
steps += 1
mean = total / len(data)
steps += 1 # 1 step
above = 0
steps += 1 # 1 step
for x in data: # pass 2: n iterations
if x > mean:
above += 1
steps += 1
return above, steps
data = [4, 8, 15, 16, 23, 42]
print(count_above_mean(data)) # (2, 15)With n = len(data), the blocks cost:
| Block | Cost |
|---|---|
| `total = 0` | 1 |
| First loop | n |
| Compute `mean` | 1 |
| `above = 0` | 1 |
| Second loop | n |
| **Total** | **2n + 3** |
For n = 6, that gives 2(6) + 3 = 15, which matches the printed counter. Treating each iteration of the second loop as one step is fine even though it holds an if. The comparison and the optional increment together take constant time, so the iteration is still a bounded amount of work.
Sequence Versus Nesting
The most common mistake in this topic is mixing up loops that come one after another with loops placed inside each other. In Python the only visible difference is indentation, and the costs differ enormously.
def sequential(n):
steps = 0
for i in range(n):
steps += 1
for j in range(n): # starts after the first loop ends
steps += 1
return steps
def nested(n):
steps = 0
for i in range(n):
for j in range(n): # runs fully on every outer iteration
steps += 1
return steps
print(sequential(100), nested(100)) # 200 10000Sequential loops cost n + n = 2n. Nested loops cost n · n = n², which the next chapter covers in detail. A useful check is to ask whether the second loop restarts on every pass of the first. If it does not, add the costs.
Blocks With Different Input Sizes
Sometimes the blocks depend on different inputs. Keep each size as its own variable.
def combined_report(a, b):
steps = 0
for x in a: # len(a) iterations
steps += 1
for y in b: # len(b) iterations
steps += 1
return steps
print(combined_report([0] * 3, [0] * 7)) # 10With n = len(a) and m = len(b), the cost is n + m. You cannot simplify this to 2n or to just n. Either list could be much larger than the other, and if b has a million items while a has three, the second loop accounts for nearly all the work. Combine the terms only when you know how the sizes are related, for example when m = n or m ≤ n is guaranteed.
Loops With Different Bounds in Sequence
The addition rule applies no matter how each loop is shaped. Count each loop with its own bounds and step size, then add the results.
import math
def mixed_bounds(n):
steps = 0
for i in range(n): # n iterations
steps += 1
for i in range(0, n, 2): # ceil(n / 2) iterations
steps += 1
for i in range(3 * n): # 3n iterations
steps += 1
for i in range(10): # 10 iterations, independent of n
steps += 1
return steps
for n in (1, 7, 50, 101):
assert mixed_bounds(n) == n + math.ceil(n / 2) + 3 * n + 10
print(mixed_bounds(7)) # 42For n = 7: 7 + 4 + 21 + 10 = 42. Note that the last loop has a fixed bound. It costs 10 steps whether n is 1 or a billion, so it acts as a constant in the sum even though it is written as a loop.
Function Calls in a Sequence
A function call counts as one step only when the called function does constant work. Otherwise, the cost of the call is the cost of the function body, and you add that cost in the place where the call appears.
def scan(items):
count = 0
for _ in items:
count += 1
return count # returns the number of iterations it ran
def pipeline(items):
steps = 0
steps += scan(items) # n
steps += scan(items) # n
steps += scan(range(5)) # 5
return steps
print(pipeline(list(range(20)))) # 45The three calls on consecutive lines are sequential blocks, so the total is n + n + 5 = 2n + 5. For n = 20 that gives 45. A line such as scan(items) looks short, but it hides a loop. Some built-in operations hide loops in the same way, and a later chapter covers them.
Conditionals: Only One Branch Runs
An if/else is also sequential: first the condition runs, then exactly one branch runs. You add the cost of the condition to the cost of the branch that is taken, not to the sum of both branches.
def process(items, detailed):
steps = 1 # evaluating the condition
if detailed:
for x in items: # n * n steps
for y in items:
steps += 1
else:
for x in items: # n steps
steps += 1
return steps
data = list(range(5))
print(process(data, True)) # 26 -> 1 + n*n
print(process(data, False)) # 6 -> 1 + nThe exact cost depends on which branch runs, so it is 1 + n² or 1 + n. If you need one bound that holds for every call, take the more expensive branch: 1 + max(n², n) = 1 + n². A later chapter on best and worst cases expands on this idea.
Which Term Dominates
Once you have a sum, the terms usually grow at different rates. Consider a function that runs a nested loop followed by a single loop, costing n² + n steps:
| n | n² | n | Share of total from n² |
|---|---|---|---|
| 10 | 100 | 10 | 90.9% |
| 100 | 10,000 | 100 | 99.0% |
| 1,000 | 1,000,000 | 1,000 | 99.9% |
As n grows, the largest term accounts for nearly the entire cost. This is why a sequence of blocks usually performs like its most expensive block. Adding a cheap linear pass after a quadratic one barely changes the running time. Adding a second quadratic pass roughly doubles it. The formal rule for dropping smaller terms belongs to the Big-O chapter. For now, keep the exact sum. You will need it when sizes are independent, as with n + m, or when you compare two versions that share the same dominant term.
Common Errors
| Error | Example | Correction |
|---|---|---|
| Multiplying sequential loops | Two back-to-back `range(n)` loops counted as n² | Add them: 2n |
| Collapsing independent sizes | Loops over `a` and `b` reported as n | Report n + m |
| Charging a call as one step | `scan(items)` counted as 1 | Charge the function's cost, n |
| Adding both branches | `if`/`else` counted as cost of both | Condition plus the branch taken, or the max for a bound |
| Ignoring fixed loops | `range(10)` treated as n | It is a constant, 10 |
Exercises
Exercise
A function runs for i in range(n) with a constant-time body, then for j in range(1, n, 3) with a constant-time body, then three constant-time assignments. Charging one step per iteration and one per assignment, what is the exact step count? Evaluate it for n = 10.
Show answer
The first loop runs n times. The second runs ceil((n - 1) / 3) times for n > 1. The assignments add 3. Total: n + ceil((n - 1) / 3) + 3. For n = 10: 10 + ceil(9 / 3) + 3 = 10 + 3 + 3 = 16.
Exercise
A function loops over a list words of length n, then loops over a list stopwords of length m. A teammate says the cost is O(n) because "there's only one real input." When is this correct, and what should you write otherwise?
Show answer
The claim holds only if m is bounded by a constant or by a multiple of n, for example a fixed stopword list of 100 entries. Otherwise the two sizes are independent and the cost is n + m.
Exercise
Function f calls scan(data) (n steps), then runs if len(data) > 100: with a branch costing n² steps and an else branch costing 1 step. Give the exact cost for each branch and a single bound that holds for all inputs.
Show answer
The condition costs 1 step. When the condition is true, the cost is n + 1 + n². When it is false, the cost is n + 1 + 1 = n + 2. A bound for all inputs takes the larger branch: n² + n + 1. The cheap branch can run only when n ≤ 100, though, so for large n the expensive branch is the one that actually runs.