Sub topic 3
Running time as a function of n
This chapter assumes you can read Python loops, index lists, and sum series such as 1 + 2 + ... + n. It builds on two earlier ideas: input size and counting basic operations.
From one measurement to a function
A stopwatch reading tells you how long one run took on one machine. It says nothing about how the algorithm behaves when the input grows. To describe that, we write the cost as a function T(n). Here n is the input size, and T(n) is the number of basic operations the algorithm performs on an input of that size.
The function combines two choices you already made:
Change either choice and you get a different T(n). Counting comparisons and counting memory reads can give different formulas for the same code. Pick one operation and state it.
Deriving T(n) by counting
Take the operation "one comparison between two list elements". Two small functions show how the count turns into a formula.
def find_max(items):
comparisons = 0
best = items[0]
for x in items[1:]:
comparisons += 1
if x > best:
best = x
return best, comparisons
def count_pair_checks(items):
checks = 0
n = len(items)
for i in range(n):
for j in range(i + 1, n):
checks += 1
return checks
print("n find_max pairs")
for n in [1, 2, 4, 8, 16]:
items = list(range(n))
print(n, find_max(items)[1], count_pair_checks(items))The output is:
n find_max pairs
1 0 0
2 1 1
4 3 6
8 7 28
16 15 120The first column of counts follows T(n) = n - 1. The loop runs once for every element except the first.
The second follows T(n) = n(n - 1) / 2. For each i the inner loop runs n - 1 - i times, so the total is (n - 1) + (n - 2) + ... + 1 + 0. That is the sum 1 + 2 + ... + (n - 1).
What the function tells you
Compare how each count changes when n doubles from 8 to 16. The find_max count goes from 7 to 15, about twice as much. The pair count goes from 28 to 120, more than four times as much. The function shows this growth directly, and a single timing could not.
| n | n - 1 | n(n - 1) / 2 |
|---|---|---|
| 10 | 9 | 45 |
| 100 | 99 | 4,950 |
| 1,000 | 999 | 499,500 |
For large n, the second algorithm is far more expensive, whatever machine runs it.
A limit of this model
Both functions above cost the same on every input of size n. find_max always makes n - 1 comparisons, whether the list is sorted or not. Many algorithms are not like this. Their count depends on the contents of the input, not only on n. Then a single T(n) is not well defined, and you must say which input of size n you mean. The next chapters handle this problem.
Exercise
The function below counts one operation each time the inner statement runs. Write T(n) as a formula and compute T(10). def f(items): n = len(items) count = 0 for i in range(n): for j in range(n): count += 1 return count
Show answer
The outer loop runs n times and the inner loop runs n times for each outer pass, so T(n) = n * n = n^2. T(10) = 100.