কম্পিউটার বিজ্ঞান · বই 2 · শ্রেণি 10–12

High School Computer Science

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: 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 nn: 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}")
Listing 17.1. Linear search, counting its comparisons. code/grade-11/06-cost-of-an-algorithm/listings/count_linear.py
$ 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
Output 17.1. The first name costs one comparison; a name that is absent costs nn.

17.2 Best and worst case

Definition 17.3 (Best case, worst case)

For a given input size nn, the best case of an algorithm is an input of size nn 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}")
Listing 17.2. Insertion sort, counting the comparisons between elements. code/grade-11/06-cost-of-an-algorithm/listings/count_insertion.py
$ 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
Output 17.2. A sorted list costs n−1n - 1 comparisons, a reversed one n(n−1)/2n(n-1)/2, and a shuffled one about half of that.
Insertion sort on six elements. Sorted: every new element is checked once against its left neighbour. Reversed: the last one, 1, is compared with all five before it on its way to the front.
Insertion sort on six elements. Sorted: every new element is checked once against its left neighbour. Reversed: the last one, 11, is compared with all five before it on its way to the front.

17.3 Constant, linear and quadratic cost

The exact count depends on details: counting assignments too, or starting the loop at 00 or 11, changes it a little. What does not change is how it grows with nn.

Definition 17.4 (Constant, linear, quadratic cost)

A cost is constant if it does not grow with nn; linear if it is about proportional to nn, so that doubling nn about doubles it; quadratic if it is about proportional to n2n^2, so that doubling nn about multiplies it by 44.

Linear search costs nn in its worst case: linear. Insertion sort costs n(n−1)/2=(n2−n)/2n(n-1)/2 = (n^2 - n)/2: for large nn the term n2/2n^2/2 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)
Listing 17.3. The worst-case counts when nn doubles. code/grade-11/06-cost-of-an-algorithm/listings/doubling.py
$ 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
Output 17.3. Doubling nn doubles the linear count and multiplies the quadratic one by 44.
Worst-case counts, from figures/counts.py. At n = 100, 100 comparisons against 4950; the straight line is not zero, it only looks flat beside the parabola.
Worst-case counts, from figures/counts.py. At n=100n = 100, 100100 comparisons against 49504950; 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 n≥1n \ge 1, the number of halvings h(n)h(n) is the number of times nn can be halved, rounding down, before it reaches 11. It is the whole number hh such that 2h≤n<2h+12^h \le n < 2^{h + 1}.

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)}")
Listing 17.4. h(n)h(n), counted, and checked against the powers of 22. code/grade-11/06-cost-of-an-algorithm/listings/halvings.py
$ 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
Output 17.4. A thousand is halved 99 times, a million 1919, a billion 2929: multiplying nn by a thousand adds about 1010.
Halving 1000, rounding down: after 9 halvings only 1 is left, so h(1000) = 9, and indeed 29 = 512 1000 < 1024.
Halving 10001000, rounding down: after 99 halvings only 11 is left, so h(1000)=9h(1000) = 9, and indeed 29=512≤1000<10242^9 = 512 \le 1000 < 1024.

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 nn elements, and each turn leaves at most half of it, rounded down. In the worst case it makes h(n)+1h(n) + 1 turns: 2020 for a million names, against a million comparisons for linear search. Its cost grows by one turn when nn 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
Listing 17.5. Timing insertion sort as nn doubles. code/grade-11/06-cost-of-an-algorithm/listings/measure_sorts.py
$ 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
Output 17.5. Measured on the author’s laptop: each doubling multiplies the time by about 44, as the quadratic count predicted.
Insertion sort on shuffled lists, median of five runs, measured on the author’s laptop (figures/measured_plot.py). The dashed lines mark n = 1000, 2000, 4000: each doubling, about four times the time.
Insertion sort on shuffled lists, median of five runs, measured on the author’s laptop (figures/measured_plot.py). The dashed lines mark n=1000n = 1000, 20002000, 40004000: 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.

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 500500 names? When is that case?

Solution

Solution of Exercise 17.1.

500500, when the name is absent, or is the last one: every element is compared.

Exercise 17.2 ★

Compute h(1000)h(1000) by halving by hand, and check it with powers of 22.

Solution

Solution of Exercise 17.2.

10001000, 500500, 250250, 125125, 6262, 3131, 1515, 77, 33, 11: nine halvings, h(1000)=9h(1000) = 9. Check: 29=512≤1000<1024=2102^9 = 512 \le 1000 < 1024 = 2^{10}.

Exercise 17.3 ★

What does count_insertion.py print for the sorted and the reversed lists if n=20n = 20?

Solution

Solution of Exercise 17.3.

1919 for the sorted list (n−1n - 1) and 190190 for the reversed one (20×19/220 \times 19 / 2); the last column prints 190190 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 n=10n = 10 and in general.

Solution

Solution of Exercise 17.4.

For each i, the inner body runs i times: 0+1+⋯+9=450 + 1 + \dots + 9 = 45 for n=10n = 10, and 0+1+⋯+(n−1)=n(n−1)/20 + 1 + \dots + (n - 1) = n(n - 1)/2 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 1010 elements, sorted makes 99.

Exercise 17.6 ★★

Selection sort compares, at turn ii, the element in place ii and those after it. Show that it makes exactly n(n−1)/2n(n-1)/2 comparisons on every list, by writing the sum (n−1)+(n−2)+⋯+1(n-1) + (n-2) + \dots + 1 twice, the second time backwards, and adding.

Solution

Solution of Exercise 17.6.

Turn ii compares place ii with the n−1−in - 1 - i places after it, whatever the values: in all S=(n−1)+(n−2)+⋯+1S = (n - 1) + (n - 2) + \dots + 1. Written backwards, S=1+2+⋯+(n−1)S = 1 + 2 + \dots + (n - 1). Adding the two lines term by term gives n−1n - 1 sums, each equal to nn: 2S=n(n−1)2S = n(n - 1), so S=n(n−1)/2S = n(n - 1)/2.

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 22 seconds for n=10 000n = 10\,000. About how long for n=30 000n = 30\,000?

Solution

Solution of Exercise 17.8.

Tripling nn multiplies a quadratic cost by 32=93^2 = 9: about 1818 seconds.

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: n(n−1)/2n(n - 1)/2 comparisons.

Exercise 17.10 ★★

Which list of length nn 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 n−1n - 1 turns.

Exercise 17.11 ★★

Write h(n) by halving, and check on all nn from 11 to 50005000 that 2h(n)≤n<2h(n)+12^{h(n)} \le n < 2^{h(n) + 1}.

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 h(n)+1h(n) + 1 turns on a list of n≥1n \ge 1 elements.

Solution

Solution of Exercise 17.12.

Let w=hi−low = \mathit{hi} - \mathit{lo} be the window’s size, nn at the start. A turn that does not return leaves either mid−lo=⌊w/2⌋\mathit{mid} - \mathit{lo} = \lfloor w/2 \rfloor elements, or hi−mid−1\mathit{hi} - \mathit{mid} - 1, which is ⌈w/2⌉−1≤⌊w/2⌋\lceil w/2 \rceil - 1 \le \lfloor w/2 \rfloor: at most half of ww, rounded down. So after kk turns the window has at most as many elements as nn halved kk times, rounding down each time. After h(n)h(n) turns that is 11, by the definition of h(n)h(n); a window of 11 element allows one more turn, after which it is empty and the loop stops. In all, at most h(n)+1h(n) + 1 turns, hence at most h(n)+1h(n) + 1 elements t[mid] looked at.

Exercise 17.13 ★★★

Rank the costs 10001000, h(n)h(n), 100n100n, n⋅h(n)n \cdot h(n) and n2n^2 at n=10n = 10, 10001000 and 10610^6. Which is smallest at n=10n = 10? Is n⋅h(n)n \cdot h(n) below 100n100n at n=106n = 10^6? What does this say about comparing costs only by their growth?

Solution

Solution of Exercise 17.13.

costn=10n = 10n=1000n = 1000n=106n = 10^6
10001000100010001000100010001000
h(n)h(n)33991919
100n100n10001000100 000100\,00010810^8
n⋅h(n)n \cdot h(n)3030900090001.9×1071.9 \times 10^7
n2n^210010010610^6101210^{12}

At n=10n = 10 the smallest is h(n)h(n), then n⋅h(n)n \cdot h(n), n2n^2, and 10001000 and 100n100n tie. At 10610^6, n⋅h(n)n \cdot h(n) is still five times below 100n100n, although it grows faster: it passes 100n100n only when h(n)h(n) passes 100100, for nn beyond 21002^{100}, a size no list will ever have. How a cost grows tells which wins for large enough nn; 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 n−1n - 1 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 n=40 000n = 40\,000. Running it would take a while: estimate how long, and say why the prediction might be off.

Solution

Solution of Exercise 17.15.

From 40004000 to 40 00040\,000 the size is multiplied by 1010, so a quadratic time by 100100: about 100100 times the time printed for n=4000n = 4000, a little under 2020 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 nn, were not negligible in the measurement at 40004000.

17.7 Problem: Two Ways to Find Duplicates

Problem 17.1

Weekend problem — from which size sorting first pays

A list of nn 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)
Listing 17.7. Three ways to find a duplicate, and a counted value. code/grade-11/06-cost-of-an-algorithm/listings/duplicates.py
"""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))
Listing 17.8. Counting the comparisons on lists without duplicates. code/grade-11/06-cost-of-an-algorithm/listings/dup_count.py
$ 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
Output 17.7. The counts, on shuffled lists of different numbers.
"""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")
Listing 17.9. Timing the three, and predicting the quadratic one at n=100 000n = 100\,000. code/grade-11/06-cost-of-an-algorithm/listings/dup_measure.py
$ 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
Output 17.8. Measured on the author’s laptop.

Part I — Every pair.

  1. Why is a list without duplicate the worst case of by_pairs?
  2. Count its comparisons on such a list of nn elements, and check the line n=100n = 100.
  3. Is its cost constant, linear or quadratic?
  4. What does Counted do, and why can it count the comparisons made inside sorted?
  5. Why is by_pairs not run at n=100 000n = 100\,000 in dup_count.py?

Part II — Sort, then scan.

  1. Why do two equal values end up side by side once the list is sorted?
  2. How many comparisons does the scan make, at most?
  3. Subtract them from the printed counts at n=10n = 10 and n=100n = 100: how many comparisons did the sort make?
  4. From the output, from which nn does sorting win, on these lists? Why did it lose for small nn?
  5. At n=100 000n = 100\,000, how many times fewer comparisons than every pair?

Part III — The measured times.

  1. Check that the times of by_pairs at 10001000, 20002000, 40004000 grow like a quadratic cost.
  2. Explain the factor 625625 in the prediction for n=100 000n = 100\,000.
  3. Express the predicted time in minutes.
  4. The set version compares nothing. Why can it still not take a constant time?
  5. Rank the three by measured time at n=100 000n = 100\,000.

Part IV — The verdict.

  1. Check the printed speed-up from the two times it divides.
  2. Why is the speed-up measured in time different from the ratio of comparisons of question 10?
  3. For a list of a thousand numbers checked once, does the choice matter? For a million?
  4. Why is the prediction for by_pairs at 100 000100\,000 reasonable but not exact?
  5. State the result: the size from which sorting needs fewer comparisons, and the speed-up measured at n=100 000n = 100\,000.
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 i<ji < j once: n(n−1)/2n(n - 1)/2. For n=100n = 100, 49504950, 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, 4 999 950 0004\,999\,950\,000, by the formula; running five billion counted comparisons in Python would take hours.

6. If s[i] == s[j] with i<ji < j, 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. n−1n - 1, one per pair of neighbours, when there is no duplicate.

8. At n=10n = 10: 32−9=2332 - 9 = 23 comparisons for the sort. At n=100n = 100: 631−99=532631 - 99 = 532.

9. From n=7n = 7, for every size up to 100100 on these lists. For small nn, the sort’s own comparisons plus the n−1n - 1 of the scan are more than all the pairs: at n=5n = 5, 1111 against 1010.

10. 4 999 950 000/1 628 843≈30704\,999\,950\,000 / 1\,628\,843 \approx 3070 times fewer.

11. 8.08.0, 32.732.7 and 129.2129.2 ms: each doubling multiplies the time by about 44.

12. 100 000/4000=25100\,000 / 4000 = 25, and a quadratic time grows like the square: 252=62525^2 = 625.

13. About 8181 s, a little under a minute and a half.

14. Building the set reads each of the nn numbers once: its cost is linear, it grows with nn.

15. The set, 5.15.1 ms; sort then scan, 20.220.2 ms; every pair, about 8181 s, predicted.

16. 81/0.0202≈400081 / 0.0202 \approx 4000, 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, 88 ms against a fraction of a millisecond: it hardly matters. For a million, the pairs would take 2502=62 500250^2 = 62\,500 times the time at n=4000n = 4000, 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 10001000 to 40004000 far beyond where it was measured.

20. On these shuffled lists of different numbers, sort then scan needs fewer comparisons than every pair from n=7n = 7 on; at n=100 000n = 100\,000 it was measured about 40004000 times faster on the author’s laptop (20.220.2 ms against about 8181 s predicted for every pair), and a set was faster still.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো