Sub topic 1
What Counts as a Step
Prerequisites
This chapter assumes you can read and write basic Python, use for and while loops, and handle basic algebra, including exponents. Later chapters also use logarithms.
What Counts as a Step
A step is an operation that takes constant time. Its cost stays the same no matter how large the input is. Assigning a variable, comparing two numbers, adding, and indexing a list are all single steps.
We ignore exact machine timings. The same code runs at different speeds depending on the hardware, the interpreter version, and the cache. The number of steps stays the same on every machine, so it is a more reliable measure of an algorithm's cost.
A common mistake is to treat every line as one step. A line such as x in my_list scans the list, so it is a loop. A later chapter covers these hidden loops.
Counting a Single Loop
A loop costs the number of times it runs multiplied by the work in its body. If the body is constant, the cost is the iteration count.
def count_single(n):
steps = 0
for i in range(n):
steps += 1
return steps
print(count_single(10)) # 10Start, Stop, and Step: Exact Iteration Counts
For a positive step s and b > a, the loop range(a, b, s) runs ceil((b - a) / s) times. If b <= a, it runs zero times. Off-by-one errors are common because range excludes its stop value. range(n) runs n times, and so does range(1, n + 1).
import math
a, b, s = 3, 20, 4
print(len(range(a, b, s))) # 5
print(math.ceil((b - a) / s)) # 5Code in Sequence: Adding Costs
When one block of code runs after another, you add their costs.
def count_sequence(n):
steps = 0
for i in range(n): # n iterations
steps += 1
for j in range(0, n, 2): # ceil(n / 2) iterations
steps += 1
return steps
print(count_sequence(10)) # 15The total is n + ceil(n / 2). Both terms grow in proportion to n, so the sum does too.
Exercise
How many times does the body of for i in range(5, 50, 7): run?
Show answer
ceil((50 - 5) / 7) = ceil(45 / 7) = 7. The values are 5, 12, 19, 26, 33, 40, and 47.
Exercise
A function runs for i in range(n): and then for j in range(3, n):, each with a constant body. What is its step count for n = 10?
Show answer
The first loop runs 10 times and the second runs 10 - 3 = 7 times, so the total is 10 + 7 = 17.