Sub topic 1
What Counts as a Step
To estimate how long an algorithm runs, you need a unit of work to count. This chapter defines that unit, the step, and explains why counting steps tells you more than a stopwatch does.
Prerequisites
This chapter assumes you can:
- Read and write basic Python code, including functions and variables.
- Follow
forandwhileloops. - Work with basic algebra, including exponents.
- Recognize logarithms. They become important in later chapters.
Why Not Just Time the Code?
Timing a program sounds like the direct approach, but the result depends on things outside your algorithm. The same function runs at different speeds on a laptop and on a server. It also changes with the Python version, and it varies when other programs compete for the CPU. Run the code below a few times and the printed times will change from run to run:
import time
def total(values):
result = 0
for v in values:
result += v
return result
data = list(range(1_000_000))
for _ in range(3):
start = time.perf_counter()
total(data)
print(f"{time.perf_counter() - start:.4f} seconds")The work the function does stays the same on every run. It adds one million numbers. Counting that work gives you a number that stays the same on any machine, so you can compare algorithms fairly and predict what happens when the input grows.
Defining a Step
A step is a basic operation whose cost does not depend on the size of the input. Each step takes some fixed amount of time, and the exact amount does not matter. Common steps include:
| Operation | Example | One step? |
|---|---|---|
| Arithmetic on small numbers | `a + b`, `x * 2` | Yes |
| Comparison | `i < n`, `x == target` | Yes |
| Assignment | `result = 0` | Yes |
| Indexing a list | `items[i]` | Yes |
| Returning a value | `return result` | Yes |
| Calling `len()` on a list | `len(items)` | Yes |
| Membership test on a list | `x in items` | No, it scans the list |
| Slicing a list | `items[1:]` | No, it copies elements |
The rule for the table is simple: if the operation's work grows with the input, it is not one step.
Some Steps Cost More Than Others, and That Is Fine
A multiplication may take longer than an assignment. Indexing a list may take longer than adding two integers. You count both as one step anyway. Every step costs between some smallest and some largest fixed amount of time, so the total running time is the step count multiplied by a constant. That constant depends on the machine, which is the part you chose to ignore. What remains is how the count grows with the input, and it grows the same way whatever constant you multiply by.
A Worked Example
Count the steps in this function, which has no loops:
def average_of_three(a, b, c):
total = a + b + c # 2 additions + 1 assignment = 3 steps
avg = total / 3 # 1 division + 1 assignment = 2 steps
return avg # 1 step
print(average_of_three(4, 8, 12)) # 8.0The total is 6 steps. Some people count total = a + b + c as a single step instead. That gives 4 steps in total, and it is just as valid. The total is a fixed number either way, and it stays the same whether the inputs are 4 or 4 billion. The exact constant does not matter. What matters is whether the count stays fixed or grows with the input. In the next chapter, loops make the count grow.
Common Errors
- Counting a line as one step when it hides a loop.
max(items)reads every element, so it costs as many steps as the list is long. - Arguing over constants. Whether an assignment counts as one step or two never changes the order of growth.
- Treating huge numbers as constant-time. Python integers can grow without limit. Arithmetic on numbers with thousands of digits is not constant time. In this tutorial, assume numbers are small enough to fit in a machine word.
Exercise
Which of these count as one step for a list items of length n: items[0], len(items), sum(items), items.append(5)?
Show answer
items[0], len(items), and items.append(5) each count as one step. (append is constant time on average.) sum(items) reads all n elements, so it costs about n steps.
Exercise
Why can you count both an addition and an assignment as one step, even though they take different amounts of real time?
Show answer
Each operation takes a fixed amount of time that does not depend on the input size. The total time is therefore the step count times a machine-dependent constant. How the count grows with the input does not change when you multiply by a constant.