এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
High School Computer Science · শ্রেণি 10–12
17The Cost of an Algorithm
Two programs look for the names that appear twice in a list. They give the same answer. On a hundred names both answer at once; on a million names, one answers in well under a second and the other takes hours. Nothing in the answers tells them apart. What tells them apart is how much work each does, and how that work grows with the size of the list.
The previous chapter proved that a loop stops and gives the right answer. This one counts how many steps it takes before it stops: exactly, by counting operations in the code, and then roughly, by timing it. The two agree in a way that lets one predict, from a small run, how long a large one will take.
You already know
Linear search, binary search, selection sort and insertion sort, with their invariants and variants, are in chapter 16. Counting the comparisons a search or a sort makes, on small lists and by hand, was done in Book 1, grade 8.
17.1 Counting elementary operations
Definition 17.1 (Elementary operation, input size)
An elementary operation is an operation whose time does not depend on the size of the data: comparing two numbers, adding them, reading or writing one element of a list. The input size is a number that measures the data, usually written : the length of a list, the number of names.
Definition 17.2 (Cost)
The cost of an algorithm on an input is the number of elementary operations it performs. One usually counts a single kind of operation that the others follow, such as the comparisons between elements in a search or a sort.
The simplest way to count is to let the program count: a variable that grows by one at each comparison.
"""Linear search, counting its comparisons."""
def search(t, x):
comparisons = 0
for i in range(len(t)):
comparisons += 1
if t[i] == x:
return i, comparisons
return None, comparisons
if __name__ == "__main__":
for n in [10, 100, 1000]:
t = [f"name{k}" for k in range(n)]
_, best = search(t, "name0")
_, worst = search(t, "nobody")
print(f"n = {n:4}: best case {best:4} comparison(s), worst case {worst:4}")
$ python count_linear.py
n = 10: best case 1 comparison(s), worst case 10
n = 100: best case 1 comparison(s), worst case 100
n = 1000: best case 1 comparison(s), worst case 1000
17.2 Best and worst case
Definition 17.3 (Best case, worst case)
For a given input size , the best case of an algorithm is an input of size on which its cost is the smallest, and the worst case one on which it is the largest. The cost in the worst case is a promise: no input of that size costs more.
Insertion sort shows how far apart the two may be. On a sorted list, each new element is compared once with the one before it and stays put. On a list in reverse order, each new element is compared with every element before it and travels to the front.
"""Insertion sort, counting the comparisons between elements."""
import random
def insertion_sort(t):
comparisons = 0
for i in range(1, len(t)):
x, j = t[i], i
while j > 0:
comparisons += 1
if t[j - 1] <= x:
break
t[j] = t[j - 1]
j -= 1
t[j] = x
return comparisons
if __name__ == "__main__":
rng = random.Random(6)
print(" n sorted shuffled reversed n(n-1)/2")
for n in [10, 100, 1000]:
shuffled = rng.sample(range(n), n)
counts = [insertion_sort(t) for t in
(list(range(n)), shuffled, list(range(n, 0, -1)))]
print(f"{n:5} {counts[0]:8} {counts[1]:9} {counts[2]:9} {n * (n - 1) // 2:10}")
$ python count_insertion.py
n sorted shuffled reversed n(n-1)/2
10 9 31 45 45
100 99 2798 4950 4950
1000 999 251757 499500 499500
17.3 Constant, linear and quadratic cost
The exact count depends on details: counting assignments too, or starting the loop at or , changes it a little. What does not change is how it grows with .
Definition 17.4 (Constant, linear, quadratic cost)
A cost is constant if it does not grow with ; linear if it is about proportional to , so that doubling about doubles it; quadratic if it is about proportional to , so that doubling about multiplies it by .
Linear search costs in its worst case: linear. Insertion sort costs : for large the term is almost all of it, and the cost is quadratic.
"""What happens to each count when n doubles."""
from count_insertion import insertion_sort
from count_linear import search
previous = None
for n in [1000, 2000, 4000]:
linear = search(list(range(n)), -1)[1] # worst case: absent
quadratic = insertion_sort(list(range(n, 0, -1))) # worst case: reversed
line = f"n = {n:4}: linear search {linear:5}, insertion sort {quadratic:9}"
if previous:
line += f" ratios {linear / previous[0]:.2f}"
line += f" and {quadratic / previous[1]:.2f}"
print(line)
previous = (linear, quadratic)
$ python doubling.py
n = 1000: linear search 1000, insertion sort 499500
n = 2000: linear search 2000, insertion sort 1999000 ratios 2.00 and 4.00
n = 4000: linear search 4000, insertion sort 7998000 ratios 2.00 and 4.00
figures/counts.py. At , comparisons against ; the straight line is not zero, it only looks flat beside the parabola.17.4 The cost of halving
Binary search does not look at the elements one by one: it halves the window each time. Its cost is the number of halvings.
Definition 17.5 (Number of halvings)
For a whole number , the number of halvings is the number of times can be halved, rounding down, before it reaches . It is the whole number such that .
def h(n):
"""The number of times n can be halved (rounding down) before it reaches 1."""
count = 0
while n > 1:
n = n // 2
count += 1
return count
print(" n h(n) 2^h(n) <= n < 2^(h(n)+1)")
for n in [1, 2, 3, 7, 8, 1000, 10**6, 10**9]:
k = h(n)
assert 2**k <= n < 2**(k + 1)
print(f"{n:10} {k:6} {2**k:>10} <= n < {2**(k + 1)}")
$ python halvings.py
n h(n) 2^h(n) <= n < 2^(h(n)+1)
1 0 1 <= n < 2
2 1 2 <= n < 4
3 1 2 <= n < 4
7 2 4 <= n < 8
8 3 8 <= n < 16
1000 9 512 <= n < 1024
1000000 19 524288 <= n < 1048576
1000000000 29 536870912 <= n < 1073741824
The binary search of the previous chapter looks at one element, t[mid], per turn, comparing it with x at most twice. Its window starts with elements, and each turn leaves at most half of it, rounded down. In the worst case it makes turns: for a million names, against a million comparisons for linear search. Its cost grows by one turn when doubles.
17.5 Measured running times
Counts predict running times, up to a factor that depends on the machine. time.perf_counter() reads a clock meant for measuring short times; the difference between two readings is the time spent between them. One run is never enough: the machine does other things at the same time, so each measurement is repeated and the median kept, the middle value, which an occasional slow run does not move.
"""Running times of insertion sort when n doubles: the median of five runs."""
import random
import statistics
import time
from count_insertion import insertion_sort
def median_time(n, rng, runs=5):
times = []
for _ in range(runs):
t = rng.sample(range(n), n) # a new shuffled list for each run
start = time.perf_counter()
insertion_sort(t)
times.append(time.perf_counter() - start)
return statistics.median(times)
rng = random.Random(1)
previous = None
for n in [1000, 2000, 4000]:
seconds = median_time(n, rng)
ratio = f" x {seconds / previous:.1f}" if previous else ""
print(f"n = {n}: {seconds * 1000:7.1f} ms{ratio}")
previous = seconds
$ python measure_sorts.py
n = 1000: 11.3 ms
n = 2000: 45.3 ms x 4.0
n = 4000: 189.4 ms x 4.2
figures/measured_plot.py). The dashed lines mark , , : each doubling, about four times the time.The same machine, looking for a number in a million: a scan of the list against a binary search and against a set, which finds an element by computing where it is stored rather than by comparing.
"""One lookup in a million numbers: a list, binary search, a set."""
import bisect
import statistics
import time
N = 10**6
numbers = list(range(0, 2 * N, 2)) # sorted, even numbers only
as_set = set(numbers)
targets = [N + 1, 2 * N - 2] # absent (odd), and the very last one
def per_lookup(found, runs=5, repeat=20):
times = []
for _ in range(runs):
start = time.perf_counter()
for _ in range(repeat):
for x in targets:
found(x)
times.append((time.perf_counter() - start) / (repeat * len(targets)))
return statistics.median(times)
def in_sorted(x):
i = bisect.bisect_left(numbers, x)
return i < len(numbers) and numbers[i] == x
for name, found in [("x in list", lambda x: x in numbers),
("binary search", in_sorted),
("x in set", lambda x: x in as_set)]:
print(f"{name:14} {per_lookup(found) * 1e6:10.3f} microseconds per lookup")
$ python measure_search.py
x in list 5855.435 microseconds per lookup
binary search 0.141 microseconds per lookup
x in set 0.033 microseconds per lookup
Remark 17.6
A timing measures everything between the two clock readings. A print inside the timed part, or building the list there, is measured too. Timings also vary from run to run and from machine to machine: this book’s timings are printed as measured once, on one laptop, and only their ratios are meant to carry over.
17.6 Exercises
Exercise 17.1 ★
How many comparisons does linear search make, in its worst case, on a list of names? When is that case?
Solution
Solution of Exercise 17.1.
, when the name is absent, or is the last one: every element is compared.
Exercise 17.2 ★
Compute by halving by hand, and check it with powers of .
Solution
Solution of Exercise 17.2.
, , , , , , , , , : nine halvings, . Check: .
Exercise 17.3 ★
What does count_insertion.py print for the sorted and the reversed lists if ?
Solution
Solution of Exercise 17.3.
for the sorted list () and for the reversed one (); the last column prints too. The shuffled column depends on the shuffle.
Exercise 17.4 ★
How many times does the body run in for i in range(n), then inside it for j in range(i)? Give the count for and in general.
Solution
Solution of Exercise 17.4.
For each i, the inner body runs i times: for , and in general, by the pairing of exercise 17.6.
Exercise 17.5 ★
Write count_comparisons(sort, t) that sorts a copy of t with a given sorting function, such as sorted, and returns how many comparisons it made. Hint: functools.cmp_to_key turns a comparison function into a key.
Solution
Solution of Exercise 17.5.
def count_comparisons(sort, t):
count = 0
def less(a, b):
nonlocal count
count += 1
return -1 if a < b else (1 if b < a else 0)
key = functools.cmp_to_key(less)
sort([key(v) for v in t])
return count
Each comparison the sort makes between two keys calls less once. On a sorted list of elements, sorted makes .
Exercise 17.6 ★★
Selection sort compares, at turn , the element in place and those after it. Show that it makes exactly comparisons on every list, by writing the sum twice, the second time backwards, and adding.
Solution
Solution of Exercise 17.6.
Turn compares place with the places after it, whatever the values: in all . Written backwards, . Adding the two lines term by term gives sums, each equal to : , so .
Exercise 17.7 ★★
A student times a sort with a print of the list after each turn, inside the timed part. Why is the measurement wrong, and what does it measure?
Solution
Solution of Exercise 17.7.
Printing a list writes every element as text and sends it to the screen, which takes far longer than a comparison. The timing then measures mostly the printing, which grows with the list printed at each turn, and depends on the terminal, not on the sort. Time the sort alone, and print afterwards.
Exercise 17.8 ★★
A quadratic cost takes seconds for . About how long for ?
Exercise 17.9 ★★
Write has_duplicate(t) that compares every pair of elements once, and give its number of comparisons when there is no duplicate.
Solution
Solution of Exercise 17.9.
def has_duplicate(t):
for i in range(len(t)):
for j in range(i + 1, len(t)):
if t[i] == t[j]:
return True
return False
Without a duplicate, every pair is compared once: comparisons.
Exercise 17.10 ★★
Which list of length is the worst case for the chapter’s largest, if one counts the assignments best = t[i]? How many are there then?
Solution
Solution of Exercise 17.10.
A list in increasing order, all different: every t[i] is larger than the best so far, so the assignment runs at each of the turns.
Exercise 17.11 ★★
Write h(n) by halving, and check on all from to that .
Solution
Solution of Exercise 17.11.
def h(n):
count = 0
while n > 1:
n //= 2
count += 1
return count
The check is a loop over range(1, 5001) with assert 2**k <= n < 2**(k + 1); the tests run it.
Exercise 17.12 ★★★
Prove that the binary search of the previous chapter makes at most turns on a list of elements.
Solution
Solution of Exercise 17.12.
Let be the window’s size, at the start. A turn that does not return leaves either elements, or , which is : at most half of , rounded down. So after turns the window has at most as many elements as halved times, rounding down each time. After turns that is , by the definition of ; a window of element allows one more turn, after which it is empty and the loop stops. In all, at most turns, hence at most elements t[mid] looked at.
Exercise 17.13 ★★★
Rank the costs , , , and at , and . Which is smallest at ? Is below at ? What does this say about comparing costs only by their growth?
Solution
Solution of Exercise 17.13.
At the smallest is , then , , and and tie. At , is still five times below , although it grows faster: it passes only when passes , for beyond , a size no list will ever have. How a cost grows tells which wins for large enough ; the constants tell what “large enough” means.
Exercise 17.14 ★★★
Write a duplicate search that sorts the list and then compares neighbours. How many comparisons does the scan make?
Solution
Solution of Exercise 17.14.
def duplicates_by_sorting(t):
s = sorted(t)
return any(s[k] == s[k + 1] for k in range(len(s) - 1))
The scan makes at most comparisons, a linear cost; the sort is the larger part, as the weekend problem measures.
Exercise 17.15 ★★★
From the three times of measure_sorts.py, predict the time of insertion sort for . Running it would take a while: estimate how long, and say why the prediction might be off.
Solution
Solution of Exercise 17.15.
From to the size is multiplied by , so a quadratic time by : about times the time printed for , a little under seconds on the author’s laptop. The prediction may be off: a list ten times larger no longer fits in the processor’s fastest memory, the machine may be busy, and the small terms of the cost, negligible at large , were not negligible in the measurement at .
17.7 Problem: Two Ways to Find Duplicates
Problem 17.1
Weekend problem — from which size sorting first pays
A list of numbers may hold a duplicate. Three functions answer: one compares every pair, one sorts the list with Python’s sorted and compares neighbours, one builds a set. The first two are counted with a value that counts each comparison made with it; the third compares nothing, it computes where each number goes.
"""Three ways to find whether a list has a duplicate, counting comparisons."""
class Counted:
"""A value that counts every comparison made with < or ==."""
count = 0
def __init__(self, v):
self.v = v
def __lt__(self, other):
Counted.count += 1
return self.v < other.v
def __eq__(self, other):
Counted.count += 1
return self.v == other.v
def by_pairs(t): # every pair once: i < j
for i in range(len(t)):
for j in range(i + 1, len(t)):
if t[i] == t[j]:
return True
return False
def by_sorting(t): # equal values end up side by side
s = sorted(t)
return any(s[k] == s[k + 1] for k in range(len(s) - 1))
def by_set(t): # no comparisons counted: hashing instead
return len(set(t)) < len(t)
"""The weekend problem, part I and II: comparisons when there is no duplicate."""
import random
from duplicates import Counted, by_pairs, by_sorting
def comparisons(find, values):
Counted.count = 0
assert not find([Counted(v) for v in values])
return Counted.count
rng = random.Random(2026)
last_loss = 1 # the last n where pairs did not lose
for n in range(2, 101):
values = rng.sample(range(10 * n), n) # n different values, shuffled
pairs = comparisons(by_pairs, values)
sorting = comparisons(by_sorting, values)
if sorting >= pairs:
last_loss = n
if n in (2, 5, 10, 20, 50, 100):
print(f"n = {n:3}: pairs {pairs:5} sort then scan {sorting:4}")
print("sort then scan needs fewer comparisons from n =", last_loss + 1, "up to 100")
for n in (1000, 10**5):
values = rng.sample(range(10 * n), n)
print(f"n = {n}: pairs {n * (n - 1) // 2} (by the formula) sort then scan",
comparisons(by_sorting, values))
$ python dup_count.py
n = 2: pairs 1 sort then scan 2
n = 5: pairs 10 sort then scan 11
n = 10: pairs 45 sort then scan 32
n = 20: pairs 190 sort then scan 80
n = 50: pairs 1225 sort then scan 268
n = 100: pairs 4950 sort then scan 631
sort then scan needs fewer comparisons from n = 7 up to 100
n = 1000: pairs 499500 (by the formula) sort then scan 9636
n = 100000: pairs 4999950000 (by the formula) sort then scan 1628843
"""The weekend problem, part III and IV: running times, median of three runs."""
import random
import statistics
import time
from duplicates import by_pairs, by_set, by_sorting
def seconds(find, values, runs=3):
times = []
for _ in range(runs):
start = time.perf_counter()
assert not find(values)
times.append(time.perf_counter() - start)
return statistics.median(times)
rng = random.Random(7)
pairs = {}
for n in (1000, 2000, 4000):
values = rng.sample(range(10 * n), n)
pairs[n] = seconds(by_pairs, values)
print(f"n = {n:6}: pairs {pairs[n] * 1000:9.1f} ms")
values = rng.sample(range(10**6), 10**5)
sorting, hashing = seconds(by_sorting, values), seconds(by_set, values)
guess = pairs[4000] * (10**5 / 4000) ** 2 # a quadratic cost: x 625
print(f"n = 100000: sort then scan {sorting * 1000:.1f} ms,"
f" set {hashing * 1000:.1f} ms")
print(f"pairs at n = 100000, from n = 4000 times 625: about {guess:.0f} s")
print(f"speed-up of sort then scan: about {guess / sorting:,.0f} times")
$ python dup_measure.py
n = 1000: pairs 8.0 ms
n = 2000: pairs 32.7 ms
n = 4000: pairs 129.2 ms
n = 100000: sort then scan 20.2 ms, set 5.1 ms
pairs at n = 100000, from n = 4000 times 625: about 81 s
speed-up of sort then scan: about 4,000 times
Part I — Every pair.
- Why is a list without duplicate the worst case of
by_pairs? - Count its comparisons on such a list of elements, and check the line .
- Is its cost constant, linear or quadratic?
- What does
Counteddo, and why can it count the comparisons made insidesorted? - Why is
by_pairsnot run at indup_count.py?
Part II — Sort, then scan.
- Why do two equal values end up side by side once the list is sorted?
- How many comparisons does the scan make, at most?
- Subtract them from the printed counts at and : how many comparisons did the sort make?
- From the output, from which does sorting win, on these lists? Why did it lose for small ?
- At , how many times fewer comparisons than every pair?
Part III — The measured times.
- Check that the times of
by_pairsat , , grow like a quadratic cost. - Explain the factor in the prediction for .
- Express the predicted time in minutes.
- The set version compares nothing. Why can it still not take a constant time?
- Rank the three by measured time at .
Part IV — The verdict.
- Check the printed speed-up from the two times it divides.
- Why is the speed-up measured in time different from the ratio of comparisons of question 10?
- For a list of a thousand numbers checked once, does the choice matter? For a million?
- Why is the prediction for
by_pairsat reasonable but not exact? - State the result: the size from which sorting needs fewer comparisons, and the speed-up measured at .
Solution
Solution of Problem 17.1.
1. It can answer False only after checking every pair; with a duplicate it may stop at the first equal pair.
2. Each pair once: . For , , as printed.
3. Quadratic.
4. It wraps a number and counts, in a variable shared by all its values, each call to < or ==. sorted compares the elements with <, so each of its comparisons calls Counted.__lt__ once and is counted.
5. Its count is known exactly, , by the formula; running five billion counted comparisons in Python would take hours.
6. If s[i] == s[j] with , everything between them in the sorted list lies between the two equal values, so is equal to them; in particular s[i + 1] == s[i].
7. , one per pair of neighbours, when there is no duplicate.
8. At : comparisons for the sort. At : .
9. From , for every size up to on these lists. For small , the sort’s own comparisons plus the of the scan are more than all the pairs: at , against .
10. times fewer.
11. , and ms: each doubling multiplies the time by about .
12. , and a quadratic time grows like the square: .
13. About s, a little under a minute and a half.
14. Building the set reads each of the numbers once: its cost is linear, it grows with .
15. The set, ms; sort then scan, ms; every pair, about s, predicted.
16. , as printed.
17. A comparison costs a different time in each: sorted compares numbers inside Python’s own fast machinery, while by_pairs runs two Python loops around each comparison; the sort also moves elements, which is counted in time but not in comparisons. Counts predict how a time grows, not the ratio between two programs.
18. For a thousand numbers checked once, ms against a fraction of a millisecond: it hardly matters. For a million, the pairs would take times the time at , more than two hours, against a fraction of a second.
19. The time also has smaller terms that the square neglects, and a large list behaves differently in the machine’s memory; the prediction extends a law measured from to far beyond where it was measured.
20. On these shuffled lists of different numbers, sort then scan needs fewer comparisons than every pair from on; at it was measured about times faster on the author’s laptop ( ms against about s predicted for every pair), and a set was faster still.