计算机科学 · 第 2 册 · 10–12 年级

High School Computer Science

本书暂未推出简体中文版。现有版本:English。

High School Computer Science · 10–12 年级

27Divide and Conquer

A teacher has 10001000 exam papers to put in alphabetical order. She splits the pile in two and gives each half to a helper; each helper splits again and passes the halves on, until someone holds a single paper, which is sorted. Then the sorted piles come back up: at each level, two sorted piles are merged into one by looking only at their top papers. Nobody ever compares two papers far apart in the order, and the work is done in a small number of rounds.

This chapter turns that idea into a method: split a problem into smaller ones of the same kind, solve them, and combine their answers. It gives merge sort, which sorts far faster than the sorts of the earlier chapters; a power computed in a handful of multiplications; and an image turned a quarter in place. It also shows where the method does not pay.

You already know

A recursive function calls itself on smaller inputs, and is proved by induction (chapter 22). Binary search halves a sorted list at each step, and its cost is the number of halvings h(n)h(n), the whole number with 2h≤n<2h+12^h \le n < 2^{h+1} (chapter 17). Insertion sort makes up to about n2/2n^2/2 comparisons (the same chapter). A picture is a grid of numbers (Book 1, grade 9).

27.1 Split, solve, combine

Definition 27.1 (Divide and conquer)

Divide and conquer is a way of designing algorithms in three steps: divide the problem into smaller problems of the same kind; solve each of them, by the same method, until they are small enough to be solved directly; combine their solutions into a solution of the whole.

Binary search is the simplest case: one comparison divides the list into two halves, only one of which can hold the value; nothing is left to combine. Its cost is the number of halvings. The algorithms below solve both halves, and their cost depends on how much the combining step costs.

Notation 27.2 (Binary logarithm)

For n>0n > 0, log⁡2n\log_2 n is the number yy with 2y=n2^y = n: log⁡28=3\log_2 8 = 3, log⁡21024=10\log_2 1024 = 10. It is the logarithm of the mathematics book, in base 22. For a whole number n≥1n \ge 1, the number of halvings is h(n)=⌊log⁡2n⌋h(n) = \lfloor \log_2 n \rfloor, the whole part of log⁡2n\log_2 n.

27.2 Merge sort

Definition 27.3 (Merge, merge sort)

To merge two sorted lists is to make one sorted list of all their elements, by repeatedly moving the smaller of their two first elements to the output. Merge sort sorts a list by splitting it into two halves, sorting each by merge sort, and merging the results; a list of 00 or 11 element is already sorted.

def merge(a, b):
    """Merge two sorted lists into one sorted list; also count the comparisons."""
    out, i, j, comparisons = [], 0, 0, 0
    while i < len(a) and j < len(b):     # invariant: out is sorted, and holds the
        comparisons += 1                 # i smallest of a and j smallest of b
        if a[i] <= b[j]:
            out.append(a[i])
            i += 1
        else:
            out.append(b[j])
            j += 1
    out += a[i:] + b[j:]                 # one of the two is empty: no comparison
    return out, comparisons


if __name__ == "__main__":
    print(merge([3, 8, 12, 20], [1, 9, 10, 25, 30]))
    print(merge([1, 2, 3], [4, 5, 6]), merge([], [7, 8]))
Listing 27.1. Merging two sorted lists, with a count of the comparisons. code/grade-12/06-divide-and-conquer/listings/merge.py
$ python merge.py
([1, 3, 8, 9, 10, 12, 20, 25, 30], 7)
([1, 2, 3, 4, 5, 6], 3) ([7, 8], 0)
Output 27.1. Lengths 44 and 55 merged in 77 comparisons; when one list runs out, the rest of the other is copied without comparing.
One step of merge. The grey elements are already in out, which is sorted and holds the smallest of a and of b. Only a[i] and b[j] are compared: the smaller is the next element.
One step of merge. The grey elements are already in out, which is sorted and holds the smallest of a and of b. Only a[i] and b[j] are compared: the smaller is the next element.
import random

from merge import merge


def merge_sort(t):
    """Return t sorted, and the number of comparisons made."""
    if len(t) <= 1:
        return list(t), 0
    mid = len(t) // 2
    left, c1 = merge_sort(t[:mid])           # divide, and solve each half
    right, c2 = merge_sort(t[mid:])
    merged, c3 = merge(left, right)          # combine
    return merged, c1 + c2 + c3


if __name__ == "__main__":
    print(merge_sort([38, 27, 43, 3, 9, 82, 10, 5]))
    rng = random.Random(6)
    t = [rng.randint(0, 999) for _ in range(1000)]
    s, c = merge_sort(t)
    print("1000 numbers:", s == sorted(t), "| comparisons:", c)
Listing 27.2. Merge sort: divide, solve both halves, combine. code/grade-12/06-divide-and-conquer/listings/merge_sort.py
$ python merge_sort.py
([3, 5, 9, 10, 27, 38, 43, 82], 17)
1000 numbers: True | comparisons: 8705
Output 27.2. Eight numbers in 1717 comparisons; a thousand in 87058705.
Merge sort on eight numbers: three levels of splitting, then three levels of merging (shaded). Each level of merging handles all eight numbers once.
Merge sort on eight numbers: three levels of splitting, then three levels of merging (shaded). Each level of merging handles all eight numbers once.

How many comparisons? Take n=2hn = 2^h. The splitting goes down hh levels, to lists of one element. At each level of merging, the merges together output all nn elements, and a merge makes at most one comparison per element output: at most nn per level, so at most n⋅h=nlog⁡2nn \cdot h = n \log_2 n in all (exercise 27.8). Insertion sort can need about n2/2n^2/2.

import random

from merge_sort import merge_sort

rng = random.Random(1)
print(f"{'n':>5} {'h':>3} {'sorted input':>13} {'random input':>13}"
      f" {'n*h':>6} {'n*n/2':>9}")
for h in range(1, 11):
    n = 2 ** h
    t = list(range(n))
    shuffled = rng.sample(t, n)
    print(f"{n:5} {h:3} {merge_sort(t)[1]:13} {merge_sort(shuffled)[1]:13}"
          f" {n * h:6} {n * n // 2:9}")
Listing 27.3. Comparisons counted, against nhn h and n2/2n^2/2. code/grade-12/06-divide-and-conquer/listings/count_vs_nlogn.py
$ python count_vs_nlogn.py
    n   h  sorted input  random input    n*h     n*n/2
    2   1             1             1      2         2
    4   2             4             5      8         8
    8   3            12            16     24        32
   16   4            32            45     64       128
   32   5            80           128    160       512
   64   6           192           307    384      2048
  128   7           448           742    896      8192
  256   8          1024          1736   2048     32768
  512   9          2304          3964   4608    131072
 1024  10          5120          8941  10240    524288
Output 27.3. A sorted input needs exactly nh/2n h / 2; a random one a little less than nhn h.
Comparisons of merge sort on random lists of 2 to 8192 numbers, from figures/comparisons.py, both axes doubling at each mark. The count stays just under n _2 n; at 8192 numbers it is 96\,178, against 33\,554\,432 for n2/2.
Comparisons of merge sort on random lists of 22 to 81928192 numbers, from figures/comparisons.py, both axes doubling at each mark. The count stays just under nlog⁡2nn \log_2 n; at 81928192 numbers it is 96 17896\,178, against 33 554 43233\,554\,432 for n2/2n^2/2.

Comparisons are not the whole cost: merge sort also copies lists. The clock agrees with the count all the same.

"""Merge sort against insertion sort, timed on the author's laptop."""
import random
import time

from merge_sort import merge_sort


def insertion_sort(t):
    t = list(t)
    for i in range(1, len(t)):
        x, j = t[i], i - 1
        while j >= 0 and t[j] > x:
            t[j + 1] = t[j]
            j -= 1
        t[j + 1] = x
    return t


def best_time(f, t, repeat=3):
    times = []
    for _ in range(repeat):
        start = time.perf_counter()
        f(t)
        times.append(time.perf_counter() - start)
    return min(times)


if __name__ == "__main__":
    rng = random.Random(2)
    for n in [250, 500, 1000, 2000, 4000]:
        t = [rng.random() for _ in range(n)]
        merge_t, insert_t = best_time(merge_sort, t), best_time(insertion_sort, t)
        ratio = insert_t / merge_t
        print(f"n = {n:4}: merge {merge_t * 1000:7.2f} ms"
              f"   insertion {insert_t * 1000:8.2f} ms   ratio {ratio:5.1f}")
Listing 27.4. Merge sort and insertion sort, timed. code/grade-12/06-divide-and-conquer/listings/measure_sorts.py
$ python measure_sorts.py
n =  250: merge    0.15 ms   insertion     0.37 ms   ratio   2.4
n =  500: merge    0.37 ms   insertion     1.70 ms   ratio   4.6
n = 1000: merge    0.76 ms   insertion     7.03 ms   ratio   9.2
n = 2000: merge    1.68 ms   insertion    30.51 ms   ratio  18.2
n = 4000: merge    3.88 ms   insertion   135.06 ms   ratio  34.8
Output 27.4. On the author’s laptop. Each doubling of nn about doubles the time of merge sort and quadruples that of insertion sort.
Times measured on the author’s laptop by figures/measured_sorts.py, on random lists of 250 to 8000 numbers. Insertion sort’s curve bends upwards like n2; merge sort’s stays near the axis, at about 8 milliseconds for 8000 numbers against about 490.
Times measured on the author’s laptop by figures/measured_sorts.py, on random lists of 250250 to 80008000 numbers. Insertion sort’s curve bends upwards like n2n^2; merge sort’s stays near the axis, at about 88 milliseconds for 80008000 numbers against about 490490.

27.3 Fast exponentiation

Computing x1000x^{1000} by multiplying by xx again and again takes 999999 multiplications. But x1000=(x500)2x^{1000} = (x^{500})^2, and x500=(x250)2x^{500} = (x^{250})^2: one problem of half the size, and one multiplication.

Method 27.4 (Fast exponentiation)

Fast exponentiation computes xnx^n from y=x⌊n/2⌋y = x^{\lfloor n/2 \rfloor}: xn=y2x^n = y^2 if nn is even, xn=y2×xx^n = y^2 \times x if nn is odd; x0=1x^0 = 1 and x1=xx^1 = x. Each step costs one or two multiplications, and there are h(n)h(n) steps: at most 2⌊log⁡2n⌋2 \lfloor \log_2 n \rfloor multiplications.

def power(x, n):
    """x to the power n, by squaring; returns (value, multiplications)."""
    if n == 0:
        return 1, 0
    if n == 1:
        return x, 0
    half, m = power(x, n // 2)          # one smaller problem, used twice
    if n % 2 == 0:
        return half * half, m + 1
    return half * half * x, m + 2


def power_loop(x, n):
    """The same, reading the binary digits of n from the right."""
    result, square = 1, x
    while n > 0:
        if n % 2 == 1:
            result *= square
        square *= square
        n //= 2
    return result


def power_mod(x, n, m):
    """x to the power n, modulo m: every intermediate value stays below m."""
    result, square = 1, x % m
    while n > 0:
        if n % 2 == 1:
            result = result * square % m
        square = square * square % m
        n //= 2
    return result


if __name__ == "__main__":
    for n in [10, 13, 64, 100, 1000]:
        value, m = power(3, n)
        print(f"3^{n:<4}: {m:2} multiplications instead of {n - 1:3};"
              f" same as the loop: {value == power_loop(3, n)}")
    print(power_mod(7, 10**18, 1_000_003), pow(7, 10**18, 1_000_003))
Listing 27.5. Fast exponentiation, recursive, with a loop, and modulo mm. code/grade-12/06-divide-and-conquer/listings/fast_power.py
$ python fast_power.py
3^10  :  4 multiplications instead of   9; same as the loop: True
3^13  :  5 multiplications instead of  12; same as the loop: True
3^64  :  6 multiplications instead of  63; same as the loop: True
3^100 :  8 multiplications instead of  99; same as the loop: True
3^1000: 14 multiplications instead of 999; same as the loop: True
32502 32502
Output 27.5. 310003^{1000} in 1414 multiplications; the modular version agrees with Python’s own pow.

The loop reads the binary digits of nn from the right: square runs through xx, x2x^2, x4x^4, x8x^8, …, and result takes in the powers whose digit is 11; 13=8+4+113 = 8 + 4 + 1 gives x13=x8⋅x4⋅xx^{13} = x^8 \cdot x^4 \cdot x. The modular version keeps every number below mm by taking the remainder after each multiplication: 710187^{10^{18}} has far too many digits to be written, but its remainder modulo 1 000 0031\,000\,003 takes fewer than 120120 multiplications of numbers below mm. Secure communication relies on exactly this computation (chapter 33).

27.4 Rotating an image by quarters

Turning a square picture a quarter turn clockwise sends the pixel in row rr, column cc to row cc, column n−1−rn - 1 - r. The simplest way writes every pixel into a new grid: it needs a second picture’s worth of memory.

def rotate_copy(grid):
    """A quarter turn clockwise, into a new grid: the row r becomes column n-1-r."""
    n = len(grid)
    out = [[None] * n for _ in range(n)]
    for r in range(n):
        for c in range(n):
            out[c][n - 1 - r] = grid[r][c]
    return out


def show(grid):
    for row in grid:
        print(" ".join(f"{x:>2}" for x in row))


if __name__ == "__main__":
    g = [[4 * r + c for c in range(4)] for r in range(4)]
    show(g)
    print("--- a quarter turn clockwise:")
    show(rotate_copy(g))
Listing 27.6. A quarter turn into a new grid. code/grade-12/06-divide-and-conquer/listings/rotate_copy.py
$ python rotate_copy.py
 0  1  2  3
 4  5  6  7
 8  9 10 11
12 13 14 15
--- a quarter turn clockwise:
12  8  4  0
13  9  5  1
14 10  6  2
15 11  7  3
Output 27.6. The first row becomes the last column.

For a picture of side 2k2^k, divide and conquer turns it in place. Cut it into four quadrants. Move each quadrant to the next place clockwise, top-left to top-right to bottom-right to bottom-left, by swapping four pixels at a time; then turn each quadrant a quarter, by the same method. Only one pixel is ever held aside.

A 4 × 4 grid turned by quadrants. First the four blocks of 2 × 2 move round clockwise, each keeping its inside unchanged (the shades follow each block); then each block is turned on its own. The result is the output of the copy above.
A 4×44 \times 4 grid turned by quadrants. First the four blocks of 2×22 \times 2 move round clockwise, each keeping its inside unchanged (the shades follow each block); then each block is turned on its own. The result is the output of the copy above.
from rotate_copy import rotate_copy, show


def rotate_in_place(grid, top=0, left=0, size=None):
    """Rotate the square block of a 2^k grid a quarter turn clockwise, in place."""
    if size is None:
        size = len(grid)
    if size == 1:
        return
    h = size // 2
    for r in range(h):                       # move the four quadrants round:
        for c in range(h):                   # top-left -> top-right -> bottom-right
            a = (top + r, left + c)          # -> bottom-left -> top-left
            b = (top + r, left + h + c)
            d = (top + h + r, left + h + c)
            e = (top + h + r, left + c)
            t = grid[e[0]][e[1]]
            grid[e[0]][e[1]] = grid[d[0]][d[1]]
            grid[d[0]][d[1]] = grid[b[0]][b[1]]
            grid[b[0]][b[1]] = grid[a[0]][a[1]]
            grid[a[0]][a[1]] = t
    for dr, dc in [(0, 0), (0, h), (h, 0), (h, h)]:
        rotate_in_place(grid, top + dr, left + dc, h)   # then turn each quadrant


if __name__ == "__main__":
    g = [[4 * r + c for c in range(4)] for r in range(4)]
    expected = rotate_copy(g)
    rotate_in_place(g)
    show(g)
    print("same as the copy:", g == expected)
Listing 27.7. The quarter turn by quadrants, in place. code/grade-12/06-divide-and-conquer/listings/rotate_quadrants.py
$ python rotate_quadrants.py
12  8  4  0
13  9  5  1
14 10  6  2
15 11  7  3
same as the copy: True
Output 27.7. The same grid as the copy.

The same function turns a real picture. arrow.pgm is a picture of 16×1616 \times 16 grey levels in a plain-text format, a short header and then one number per pixel; the program turns it, writes it to a file, reads it back, and prints both as characters.

"""Read a PGM picture, turn it a quarter by quadrants, write it back."""
import tempfile
from pathlib import Path

from rotate_copy import rotate_copy
from rotate_quadrants import rotate_in_place


def read_pgm(path):
    words = Path(path).read_text().split()
    width, height = int(words[1]), int(words[2])
    values = [int(w) for w in words[4:]]
    return [values[r * width:(r + 1) * width] for r in range(height)]


def write_pgm(path, grid):
    rows = "\n".join(" ".join(str(v) for v in row) for row in grid)
    Path(path).write_text(f"P2\n{len(grid[0])} {len(grid)}\n255\n{rows}\n")


def as_text(grid):
    return ["".join("#" if v < 100 else ("+" if v < 200 else ".") for v in row)
            for row in grid]


picture = read_pgm("arrow.pgm")
turned = [row[:] for row in picture]
rotate_in_place(turned)
with tempfile.TemporaryDirectory() as folder:
    write_pgm(Path(folder) / "arrow_turned.pgm", turned)
    again = read_pgm(Path(folder) / "arrow_turned.pgm")
for before, after in zip(as_text(picture), as_text(again)):
    print(before, "  ", after)
print("same as the copy:", again == rotate_copy(picture), "| pixel sum:",
      sum(map(sum, picture)), sum(map(sum, again)))
Listing 27.8. A picture turned by quadrants. code/grade-12/06-divide-and-conquer/listings/rotate_image.py
$ python rotate_image.py
................    ................
................    ................
.......##.......    .++.....#.......
......####......    .+......##......
.....######.....    ........###.....
....########....    ........####....
...##########...    .############...
..############..    .#############..
......####......    .#############..
......####......    .############...
......####......    ........####....
......####......    ........###.....
......####......    ........##......
..+...####......    ........#.......
..++..####......    ................
................    ................
same as the copy: True | pixel sum: 43850 43850
Output 27.8. The arrow pointing up now points right; the small mark at the bottom left went to the top left.

27.5 When it pays, and when it does not

Divide and conquer pays when the parts are of similar sizes and combining is cheap. If a split leaves one part almost as large as the whole, as in a split that cuts off one element, the levels are nn instead of log⁡2n\log_2 n, and a merge sort built that way is no faster than insertion sort. On very small inputs, the calls and copies cost more than they save: at n=250n = 250 merge sort is only about twice as fast. Real sorting functions, Python’s sorted among them, merge runs of elements but finish small pieces by insertion.

Remark 27.5

The method also finds the largest sum of consecutive elements of a list: the best block lies in the left half, or in the right half, or straddles the middle, and the third case is found in one pass from the middle outwards (exercise 27.15).

27.6 Exercises

Exercise 27.1 ★

Merge [2,5,9][2, 5, 9] and [1,6,7,11][1, 6, 7, 11] step by step. How many comparisons?

Solution

Solution of Exercise 27.1.

1<21 < 2: out 11. 2<62 < 6: 22. 5<65 < 6: 55. 9>69 > 6: 66. 9>79 > 7: 77. 9<119 < 11: 99. The first list is empty, and 1111 is copied. The result is [1,2,5,6,7,9,11][1, 2, 5, 6, 7, 9, 11], after 66 comparisons.

Exercise 27.2 ★

What are the smallest and the largest numbers of comparisons when merging a list of 33 elements with one of 44? Give an example of each.

Solution

Solution of Exercise 27.2.

At least 33: each comparison outputs one element, and a list must run out; [1,2,3][1, 2, 3] with [4,5,6,7][4, 5, 6, 7] needs exactly 33. At most 3+4−1=63 + 4 - 1 = 6: the last element is always copied without comparing; [2,4,6][2, 4, 6] with [1,3,5,7][1, 3, 5, 7] needs 66.

Exercise 27.3 ★

Draw the splits and the merges of merge_sort on [5,2,4,6,1,3][5, 2, 4, 6, 1, 3].

Solution

Solution of Exercise 27.3.

Splits: [5,2,4][5, 2, 4] and [6,1,3][6, 1, 3]; then [5][5] and [2,4][2, 4], [6][6] and [1,3][1, 3]; then [2][2], [4][4], [1][1], [3][3]. Merges: [2,4][2, 4] and [1,3][1, 3]; then [2,4,5][2, 4, 5] and [1,3,6][1, 3, 6]; then [1,2,3,4,5,6][1, 2, 3, 4, 5, 6].

Exercise 27.4 ★

List the multiplications power(x, 13) makes. How many are there?

Solution

Solution of Exercise 27.4.

power(x, 13) asks for power(x, 6), which asks for power(x, 3), which asks for power(x, 1), xx, with no multiplication. Then x⋅x⋅x=x3x \cdot x \cdot x = x^3 (two), x3⋅x3=x6x^3 \cdot x^3 = x^6 (one), x6⋅x6⋅x=x13x^6 \cdot x^6 \cdot x = x^{13} (two): five multiplications.

Exercise 27.5 ★

Write merge_desc(a, b), which merges two lists sorted in decreasing order.

Solution

Solution of Exercise 27.5.

The merge of the chapter with the comparison reversed: if a[i] >= b[j]: takes from a, otherwise from b; after the loop, return out + a[i:] + b[j:].

Exercise 27.6 ★★

A merge has no line after its loop. What does it return for [1, 4, 9] and [2, 3]? Which tests would have caught it?

Solution

Solution of Exercise 27.6.

[1, 2, 3]: when b runs out, 44 and 99 are still in a, and nothing copies them. A test with lists of different lengths, or where one list ends long before the other, catches it; so does checking len(out) == len(a) + len(b), or comparing with sorted(a + b) on random lists.

Exercise 27.7 ★★

The matrix (1110)n\begin{pmatrix} 1 & 1 \\ 1 & 0 \end{pmatrix}^n holds the Fibonacci number fib(n)\mathrm{fib}(n) in its top right corner. Write fib(n) with fast exponentiation of 2×22 \times 2 matrices.

Solution

Solution of Exercise 27.7.

def mat_mult(p, q):

return [[sum(p[i][k] * q[k][j] for k in range(2)) for j in range(2)]

for i in range(2)]

def fib(n):

result, square = [[1, 0], [0, 1]], [[1, 1], [1, 0]]

while n > 0:

if n % 2 == 1:

result = mat_mult(result, square)

square = mat_mult(square, square)

n //= 2

return result[0][1]

The loop of power_loop, with matrices and the identity matrix as starting value. fib(90) takes 1111 matrix products, against 8989 additions in a loop, and the recursion of chapter 22 would never finish.

Exercise 27.8 ★★

Prove by induction on hh that merge sort makes at most nhn h comparisons on a list of n=2hn = 2^h elements.

Solution

Solution of Exercise 27.8.

Let C(h)C(h) be the largest number of comparisons on 2h2^h elements. C(0)=0=20×0C(0) = 0 = 2^0 \times 0. For h≥1h \ge 1, the two halves have 2h−12^{h-1} elements each, so at most C(h−1)C(h - 1) comparisons each, and merging them makes at most 2h−12^h - 1. If C(h−1)≤2h−1(h−1)C(h - 1) \le 2^{h-1}(h - 1), then C(h)≤2⋅2h−1(h−1)+2h−1<2hhC(h) \le 2 \cdot 2^{h-1}(h - 1) + 2^h - 1 < 2^h h.

Exercise 27.9 ★★

Turn the grid of letters with rows ab, cd a quarter clockwise. Then turn the 4×44 \times 4 grid with rows abcd, efgh, ijkl, mnop by quadrants, giving the grid after each of the two stages.

Solution

Solution of Exercise 27.9.

ab, cd becomes ca, db. For the 4×44 \times 4 grid, moving the quadrants gives the rows ijab, mnef, klcd, opgh; turning each quadrant gives miea, njfb, okgc, plhd. Check: the first row of the result is the first column read upwards.

Exercise 27.10 ★★

In merge_sort, a student writes mid = len(t) // 2 + 1. What happens on a list of two elements?

Solution

Solution of Exercise 27.10.

mid is 22: the left half is the whole list and the right half is empty. The call on the left half is the same call again, and so on, until RecursionError. A division must give two parts both smaller than the whole; len(t) // 2 does for every length at least 22.

Exercise 27.11 ★★

Write a merge sort without recursion: start from runs of one element, and merge the runs two by two until one is left.

Solution

Solution of Exercise 27.11.

def merge_sort_bottom_up(t):

runs = [[x] for x in t]

while len(runs) > 1:

runs = [merge(runs[k], runs[k + 1])[0]

if k + 1 < len(runs) else runs[k]

for k in range(0, len(runs), 2)]

return runs[0] if runs else []

Each pass halves the number of runs (an odd one out waits for the next pass): h(n)+1h(n) + 1 passes at most, each merging all nn elements, the same work as the recursive version.

Exercise 27.12 ★★★

Prove that power(x, n) makes at most 2⌊log⁡2n⌋2 \lfloor \log_2 n \rfloor multiplications for n≥1n \ge 1, and exactly (number of binary digits of nn −1- 1) ++ (number of digits 11 −1- 1).

Solution

Solution of Exercise 27.12.

Write b(n)b(n) for the number of binary digits of nn and o(n)o(n) for its number of digits 11; claim m(n)=(b(n)−1)+(o(n)−1)m(n) = (b(n) - 1) + (o(n) - 1). For n=1n = 1: 0=0+00 = 0 + 0. For n≥2n \ge 2, ⌊n/2⌋\lfloor n/2 \rfloor is nn without its last binary digit: b(⌊n/2⌋)=b(n)−1b(\lfloor n/2 \rfloor) = b(n) - 1 and o(⌊n/2⌋)=o(n)−(n mod 2)o(\lfloor n/2 \rfloor) = o(n) - (n \bmod 2). The call makes 1+(n mod 2)1 + (n \bmod 2) multiplications more than the call on ⌊n/2⌋\lfloor n/2 \rfloor, so by induction m(n)=(b(n)−2)+(o(n)−(n mod 2)−1)+1+(n mod 2)=(b(n)−1)+(o(n)−1)m(n) = (b(n) - 2) + (o(n) - (n \bmod 2) - 1) + 1 + (n \bmod 2) = (b(n) - 1) + (o(n) - 1). Since o(n)≤b(n)o(n) \le b(n) and b(n)−1=⌊log⁡2n⌋b(n) - 1 = \lfloor \log_2 n \rfloor, m(n)≤2⌊log⁡2n⌋m(n) \le 2 \lfloor \log_2 n \rfloor. For 10001000, written with 1010 digits of which 66 are 11: 9+5=149 + 5 = 14, as printed.

Exercise 27.13 ★★★

Write rotate_layers(grid), which turns a square grid of any side in place, ring by ring from the outside, four pixels at a time. Test it against rotate_copy.

Solution

Solution of Exercise 27.13.

def rotate_layers(grid):

n = len(grid)

for layer in range(n // 2):

first, last = layer, n - 1 - layer

for k in range(last - first):

top = grid[first][first + k]

grid[first][first + k] = grid[last - k][first]

grid[last - k][first] = grid[last][last - k]

grid[last][last - k] = grid[first + k][last]

grid[first + k][last] = top

Each ring is turned by moving four cells at a time: left side to top, bottom to left, right to bottom, top to right. It works for every side, odd ones too (the centre stays). The tests compare it with rotate_copy on random grids of sides 11 to 88.

Exercise 27.14 ★★★

Show that for n=2hn = 2^h, merge sort makes at least nh/2n h / 2 comparisons on every input: whatever the order, its count is within a factor 22 of nlog⁡2nn \log_2 n.

Solution

Solution of Exercise 27.14.

A merge of two lists of pp elements each makes at least pp comparisons: each comparison outputs one element, and the loop stops only when one list is empty. At the level where blocks of 2k2^k elements are merged in pairs, there are n/2k+1n / 2^{k+1} merges of at least 2k2^k comparisons: at least n/2n/2 per level, and there are hh levels. So the count lies between nh/2n h / 2 and nhn h, whatever the input; the program’s sorted input reaches the lower bound exactly.

Exercise 27.15 ★★★

Write max_subarray(t), the largest sum of a block of consecutive elements of a non-empty list, by divide and conquer. Test it against the sums of all blocks.

Solution

Solution of Exercise 27.15.

def max_subarray(t):

if len(t) == 1:

return t[0]

mid = len(t) // 2

best = max(max_subarray(t[:mid]), max_subarray(t[mid:]))

s, left = 0, t[mid - 1]

for x in reversed(t[:mid]):

s += x

left = max(left, s)

s, right = 0, t[mid]

for x in t[mid:]:

s += x

right = max(right, s)

return max(best, left + right)

A block straddling the middle is a block ending at mid - 1 followed by one starting at mid; each part is best chosen on its own. For [2,−5,3,4,−1,6,−8,2][2, -5, 3, 4, -1, 6, -8, 2]: 3+4−1+6=123 + 4 - 1 + 6 = 12. The tests compare with the sums of all blocks on 200200 random lists.

27.7 Problem: Counting Inversions

Problem 27.1

Weekend problem — how far apart are two rankings?

Two judges rank the same items. Writing the second ranking in terms of the first’s positions gives a list; each pair of items the judges order differently is an inversion of that list, a pair of positions i<ji < j with t[i]>t[j]t[i] > t[j]. The program counts inversions by trying every pair, and by a merge sort that counts them on the way.

"""How far apart are two rankings? Count the pairs they put in opposite orders."""
import random

from merge import merge


def inversions_brute(t):
    n = len(t)
    return sum(1 for i in range(n) for j in range(i + 1, n) if t[i] > t[j])


def sort_count(t):
    """Return t sorted and its number of inversions, by merge sort."""
    if len(t) <= 1:
        return list(t), 0
    mid = len(t) // 2
    left, x = sort_count(t[:mid])
    right, y = sort_count(t[mid:])
    across, i = 0, 0
    for b in right:                      # pairs (a in left, b in right) with a > b
        while i < len(left) and left[i] <= b:
            i += 1
        across += len(left) - i          # every a from left[i] on is larger than b
    return merge(left, right)[0], x + y + across


def ranking(n, seed):
    items = list(range(n))
    random.Random(seed).shuffle(items)
    return items


def compare(first, second):
    """Inversions of second, written in the positions of first."""
    place = {item: k for k, item in enumerate(first)}
    return [place[item] for item in second]
Listing 27.9. Inversions, by brute force and by merging. code/grade-12/06-divide-and-conquer/listings/inversions.py
if __name__ == "__main__":
    judge_a = ["Ada", "Ben", "Cleo", "Dev", "Eli"]
    judge_b = ["Ben", "Ada", "Eli", "Cleo", "Dev"]
    t = compare(judge_a, judge_b)
    print(t, "brute force:", inversions_brute(t), "| by merging:", sort_count(t)[1])
    n = 100_000
    t = compare(ranking(n, 1), ranking(n, 2))
    count = sort_count(t)[1]
    print(f"n = {n}: {count} inversions out of {n * (n - 1) // 2} pairs,"
          f" {count / (n * (n - 1) / 2):.4f} of them")
Listing 27.10. Two judges, then two random rankings. code/grade-12/06-divide-and-conquer/listings/inversions.py
$ python inversions.py
[1, 0, 4, 2, 3] brute force: 3 | by merging: 3
n = 100000: 2488902981 inversions out of 4999950000 pairs, 0.4978 of them
Output 27.9. Two judges of five, then two random rankings of 100 000100\,000 items.
"""Brute force against merging, timed on the author's laptop."""
import time

from inversions import compare, inversions_brute, ranking, sort_count


def timed(f, t):
    start = time.perf_counter()
    result = f(t)
    return result, time.perf_counter() - start


for n in [1000, 2000, 4000, 8000]:
    t = compare(ranking(n, 1), ranking(n, 2))
    brute, t_brute = timed(inversions_brute, t)
    (_, merged), t_merge = timed(sort_count, t)
    print(f"n = {n:4}: brute {t_brute:6.3f} s   merging {t_merge:6.3f} s"
          f"   ratio {t_brute / t_merge:5.0f}   same count: {brute == merged}")
_, t_merge = timed(sort_count, compare(ranking(100_000, 1), ranking(100_000, 2)))
print(f"n = 100000: merging {t_merge:.2f} s")
Listing 27.11. The two methods, timed. code/grade-12/06-divide-and-conquer/listings/measure_inversions.py
$ python measure_inversions.py
n = 1000: brute  0.016 s   merging  0.002 s   ratio    10   same count: True
n = 2000: brute  0.056 s   merging  0.003 s   ratio    21   same count: True
n = 4000: brute  0.213 s   merging  0.006 s   ratio    37   same count: True
n = 8000: brute  0.867 s   merging  0.012 s   ratio    73   same count: True
n = 100000: merging 0.20 s
Output 27.10. On the author’s laptop. Brute force is not even tried at 100 000100\,000.

Part I — Rankings.

  1. In the example of five, which pairs do the judges order differently?
  2. What list does compare give for two identical rankings, and how many inversions? For two opposite rankings of nn items?
  3. Why is the number of inversions at most n(n−1)/2n(n - 1)/2?
  4. Two random rankings: what share of the pairs would you guess to be inverted? Compare with the output.

Part II — Brute force.

  1. How many pairs does inversions_brute examine for nn items?
  2. From the measured times, by how much does the brute-force time grow when nn doubles? Why?
  3. Estimate its time for n=100 000n = 100\,000 from the time at 80008000.

Part III — Counting while merging.

  1. Split the inversions of a list into three kinds, by where their two positions lie.
  2. Which two kinds do the recursive calls count?
  3. Why can the third kind be counted on the two sorted halves, although sorting changed the positions?
  4. Explain the loop over right: why is len(left) - i the number of inversions with b?
  5. Why does i never go back, and what does that make the cost of the loop?
  6. Prove, by induction on the length, that sort_count returns the number of inversions.

Part IV — Cost and speed.

  1. How many comparisons does sort_count make, roughly, for n=2hn = 2^h?
  2. Read the measured ratio of the two methods at each nn. How does it grow?
  3. From your estimate of question 7, what would the ratio be at 100 000100\,000?
  4. From n=1000n = 1000 to n=8000n = 8000, compare the growth of the measured ratio with that of n/log⁡2nn / \log_2 n.
  5. The brute-force method is still useful. For what?
  6. The tests check the count at 100 000100\,000 against no brute force. What do they check instead?
  7. State the result: the inversions between the two rankings of 100 000100\,000, and the measured ratio at 80008000.
Solution

Solution of Problem 27.1.

1. compare gives [1,0,4,2,3][1, 0, 4, 2, 3]. The inverted pairs: Ada and Ben; Cleo and Eli; Dev and Eli.

2. Identical rankings give [0,1,…,n−1][0, 1, \dots, n - 1], with no inversion. Opposite rankings give [n−1,…,1,0][n - 1, \dots, 1, 0]: every pair is inverted, n(n−1)/2n(n - 1)/2 inversions.

3. An inversion is a pair of positions, and there are n(n−1)/2n(n - 1)/2 pairs.

4. About half: in a random ranking each pair is as likely in one order as in the other. The output gives 0.49780.4978.

5. n(n−1)/2n(n - 1)/2: every pair.

6. About four times: the printed run gives 0.0160.016, 0.0560.056, 0.2130.213 and 0.8670.867 seconds (another run gives slightly different times). Doubling nn about quadruples the number of pairs.

7. 0.867×(100 000/8000)2=0.867×156.25≈1350.867 \times (100\,000 / 8000)^2 = 0.867 \times 156.25 \approx 135 seconds, over two minutes.

8. Both positions in the left half; both in the right half; one in each.

9. The calls on the halves count the first two kinds, x and y.

10. A pair across the middle joins an element of the left half and one of the right half, and whether the first is larger depends only on the two values, not on where they sit in their halves. Sorting each half moves values only within it.

11. left is sorted, and the while loop stops at the first left[i] larger than b: every element from there on is larger than b, every one before is not. So exactly len(left) - i elements of the left half form an inversion with b.

12. right is sorted, so each b is at least the one before, and the first element of left larger than it can only be further right. i moves at most len(left) times in all: the loop costs at most len(left) + len(right) steps, like a merge.

13. For a list of 00 or 11 element, no pair: 00. Otherwise, by induction x and y are the inversions within each half, and across counts those across, by questions 10 and 11; every inversion is of exactly one kind, so the sum is the number of inversions. The returned list is sorted, by the proof of merge sort.

14. The merges make at most nhn h comparisons and the counting loops about nhn h more: about 2nlog⁡2n2 n \log_2 n, against n2/2n^2 / 2 pairs for brute force.

15. 1010, 2121, 3737, 7373 in the printed run: it about doubles each time nn doubles.

16. About 135/0.20≈680135 / 0.20 \approx 680, that is, about 700700.

17. n/log⁡2nn / \log_2 n goes from about 100100 to about 617617, a factor of about 6.26.2; the measured ratio goes from 1010 to 7373, a factor of about 77. They grow at a similar pace; the rest is the different work per step of the two methods, and the noise of the measurements, large for times of a few milliseconds.

18. As a reference: it is too simple to be wrong, and on small lists it checks the fast method.

19. They compare the fast count with brute force on random lists of every length up to 5959, and keep the count at 100 000100\,000 fixed to the value printed, so that any later change to the code that alters it is noticed.

20. The two random rankings of 100 000100\,000 items differ on 2 488 902 9812\,488\,902\,981 of their 4 999 950 0004\,999\,950\,000 pairs (0.49780.4978); at n=8000n = 8000, counting by merging was about 7070 times faster than trying every pair (7373 in the printed run), and about 700700 times is expected at 100 000100\,000.

本章定义的术语

在术语表中查看全部 1050 个术语