计算机科学 · 第 3 册 · 本科一年级

University Computer Science — Year 1

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

University Computer Science — Year 1 · 本科一年级

11Induction, Recursion and Termination

A function reverses a list; applied twice, it should give the list back. A program can check this on three thousand lists in a fraction of a second, and it does below, but lists have no largest length: a check, however long, says nothing about the lists it did not try. This chapter gives the two tools that cover every case. Structural induction proves a property of every list, tree or formula by following the rules that build them. Well-founded orders prove that a loop or a recursive function stops, by attaching to each state a quantity that cannot decrease forever.

You already know

To prove a property P(n)P(n) for every natural number nn by induction, prove P(0)P(0), and prove P(n+1)P(n + 1) from P(n)P(n) (or from all of P(0),…,P(n)P(0), \dots, P(n): strong induction). An order relation is reflexive, antisymmetric and transitive. A recursive function calls itself on smaller arguments and stops on base cases.

11.1 Inductively defined sets

Definition 11.1 (Inductively defined set)

A set is inductively defined by rules when it is the smallest set closed under them: base rules put given elements in the set, and construction rules build an element from elements already in it. Every element is obtained by finitely many applications of the rules.

The natural numbers are defined by the base rule “0” and the rule “if nn, then n+1n + 1”; the lists of the elements of a set AA by “the empty list” and “if x∈Ax \in A and ℓ\ell is a list, then xx followed by ℓ\ell”; the propositional formulas of Chapter 10 by their variables and connectives.

Definition 11.2 (Rooted tree, root, child, leaf, internal node, subtree)

A rooted tree is a node, its root, holding a key and a finite sequence of rooted trees, the subtrees of the root; the roots of these subtrees are the children of the root, which is their parent. A node without children is a leaf; the others are internal nodes. The subtrees of a tree are the tree and the subtrees of its subtrees.

Definition 11.3 (Binary tree, full binary tree)

The set of binary trees is defined inductively: the empty tree is a binary tree, and if ℓ\ell and rr are binary trees and kk a key, the node (ℓ,k,r)(\ell, k, r), with left subtree ℓ\ell and right subtree rr, is a binary tree. A binary tree is full if every node has either two non-empty subtrees or two empty ones.

Definition 11.4 (Depth, size, height)

The depth of a node is the number of links from the root to it. The size of a binary tree is its number of nodes, 0 for the empty tree. Its height is the largest depth of its nodes, and −1-1 for the empty tree: by induction, h(empty)=−1h(\text{empty}) = -1 and h((ℓ,k,r))=1+max⁡(h(ℓ),h(r))h((\ell, k, r)) = 1 + \max(h(\ell), h(r)).

@dataclass(frozen=True)
class Node:
    left: "Node | None"  # None is the empty tree
    key: int
    right: "Node | None"


def size(t):
    return 0 if t is None else 1 + size(t.left) + size(t.right)


def height(t):
    return -1 if t is None else 1 + max(height(t.left), height(t.right))


def leaves(t):
    if t is None:
        return 0
    if t.left is None and t.right is None:
        return 1
    return leaves(t.left) + leaves(t.right)


def shapes(h):
    """All binary trees of height at most h, keys 0: rule 1 gives the empty
    tree, rule 2 builds a node from two trees already built."""
    if h < 0:
        return [None]
    smaller = shapes(h - 1)
    return [None] + [Node(a, 0, b) for a in smaller for b in smaller]
Listing 11.1. Binary trees, and every tree of height at most hh code/bachelor-1/11-induction-and-termination/listings/inductive.py
$ python inductive.py
size 4 height 2 leaves 2
empty tree: size 0 height -1
height <= -1:   1 trees, largest size  0, 2^(h+1) - 1 =  0
height <=  0:   2 trees, largest size  1, 2^(h+1) - 1 =  1
height <=  1:   5 trees, largest size  3, 2^(h+1) - 1 =  3
height <=  2:  26 trees, largest size  7, 2^(h+1) - 1 =  7
height <=  3: 677 trees, largest size 15, 2^(h+1) - 1 = 15
Output 11.1. A tree of four nodes, the empty tree, and the trees produced by the rules up to height 3.

shapes applies the rules literally: the trees of height at most hh are the empty tree and the nodes built from two trees of height at most h−1h - 1, so their number aha_h satisfies a−1=1a_{-1} = 1 and ah=1+ah−12a_h = 1 + a_{h-1}^2. The convention −1-1 for the empty tree makes this rule, and the bounds below, hold without exceptions.

The two rules that generate binary trees, and what they produce from trees of height at most 0 (the empty tree, dashed, and the single node). Height -1, 0, 1, 1 and 1; the last tree is full.
The two rules that generate binary trees, and what they produce from trees of height at most 0 (the empty tree, dashed, and the single node). Height −1-1, 0, 1, 1 and 1; the last tree is full.

11.2 Structural induction

Definition 11.5 (Structural induction)

To prove a property PP of every element of an inductively defined set by structural induction, prove that PP holds for the elements given by the base rules, and that each construction rule, applied to elements satisfying PP, builds an element satisfying PP.

Proposition 11.6 (Structural induction is sound)

If the two parts of a structural induction are proved, then PP holds for every element of the set.

Proof. Every element is built by finitely many applications of the rules; call its rank the least number of rule applications in such a construction. We prove “PP holds for every element of rank at most nn” by induction on n≥1n \geq 1. An element of rank 1 comes from a base rule: PP holds. An element of rank n+1n + 1 comes from a construction rule applied to elements of smaller rank, which satisfy PP by the induction hypothesis, so it satisfies PP. (For binary trees, an induction on the height does the same work.) ∎

Proposition 11.7 (Size, height and leaves of a binary tree)

A binary tree of height hh has a size nn with h+1≤n≤2h+1−1h + 1 \leq n \leq 2^{h + 1} - 1. A full non-empty binary tree has one more leaf than internal nodes.

Proof. By structural induction. The empty tree has h=−1h = -1 and n=0=h+1=20−1n = 0 = h + 1 = 2^0 - 1. For a node with subtrees of heights hℓh_\ell, hrh_r and sizes nℓn_\ell, nrn_r satisfying the bounds, h=1+max⁡(hℓ,hr)h = 1 + \max(h_\ell, h_r) and n=1+nℓ+nrn = 1 + n_\ell + n_r. The higher subtree alone has at least max⁡(hℓ,hr)+1=h\max(h_\ell, h_r) + 1 = h nodes, so n≥h+1n \geq h + 1; and n≤1+2(2h−1)=2h+1−1n \leq 1 + 2(2^{h} - 1) = 2^{h + 1} - 1, since both heights are at most h−1h - 1. For full trees: a single node has one leaf and no internal node. A node with two non-empty full subtrees having fℓ=iℓ+1f_\ell = i_\ell + 1 and fr=ir+1f_r = i_r + 1 leaves has fℓ+fr=iℓ+ir+2f_\ell + f_r = i_\ell + i_r + 2 leaves and iℓ+ir+1i_\ell + i_r + 1 internal nodes, itself included. ∎

The induction step for full trees: each subtree has one more leaf than internal nodes, and the root adds one internal node and no leaf, so the whole tree keeps the difference of one. Leaves are pale, internal nodes shaded.
The induction step for full trees: each subtree has one more leaf than internal nodes, and the root adds one internal node and no leaf, so the whole tree keeps the difference of one. Leaves are pale, internal nodes shaded.

Lists are proved about in the same way. With the recursive definition rev([ ])=[ ]\mathit{rev}([\,]) = [\,] and rev([x]+ℓ)=rev(ℓ)+[x]\mathit{rev}([x] + \ell) = \mathit{rev}(\ell) + [x], first prove rev(ℓ+m)=rev(m)+rev(ℓ)\mathit{rev}(\ell + m) = \mathit{rev}(m) + \mathit{rev}(\ell) by induction on ℓ\ell: for ℓ=[ ]\ell = [\,] both sides are rev(m)\mathit{rev}(m); and rev([x]+ℓ+m)=rev(ℓ+m)+[x]=rev(m)+rev(ℓ)+[x]=rev(m)+rev([x]+ℓ)\mathit{rev}([x] + \ell + m) = \mathit{rev}(\ell + m) + [x] = \mathit{rev}(m) + \mathit{rev}(\ell) + [x] = \mathit{rev}(m) + \mathit{rev}([x] + \ell). Then rev(rev(ℓ))=ℓ\mathit{rev}(\mathit{rev}(\ell)) = \ell by induction on ℓ\ell: rev(rev([x]+ℓ))=rev(rev(ℓ)+[x])=rev([x])+rev(rev(ℓ))=[x]+ℓ\mathit{rev}(\mathit{rev}([x] + \ell)) = \mathit{rev}(\mathit{rev}(\ell) + [x]) = \mathit{rev}([x]) + \mathit{rev}(\mathit{rev}(\ell)) = [x] + \ell.

def rev(xs):
    """rev([]) = [];  rev([x] + rest) = rev(rest) + [x]."""
    return [] if not xs else rev(xs[1:]) + [xs[0]]


if __name__ == "__main__":
    print(rev([1, 2, 3, 4]), rev(rev([1, 2, 3, 4])))
    checked = 0
    for n in range(8):
        for xs in product(range(3), repeat=n):  # every list of length n over {0, 1, 2}
            xs = list(xs)
            assert rev(rev(xs)) == xs
            assert all(rev(xs[:k] + xs[k:]) == rev(xs[k:]) + rev(xs[:k])
                       for k in range(n + 1))
            checked += 1
    print(checked, "lists checked; a check is not a proof: see the induction")
Listing 11.2. Reverse, and a check on 3280 lists code/bachelor-1/11-induction-and-termination/listings/reverse_twice.py
$ python reverse_twice.py
[4, 3, 2, 1] [1, 2, 3, 4]
3280 lists checked; a check is not a proof: see the induction
Output 11.2. The check passes; the proof above covers the lists it did not try.

The first lemma was needed because the property of rev(rev(ℓ))\mathit{rev}(\mathit{rev}(\ell)) alone does not carry through the induction step: proving a stronger or more general statement is often what makes an induction go through.

11.3 Well-founded orders

Definition 11.8 (Strict order, minimal element, immediate predecessor)

A strict order << on a set is irreflexive (x<xx < x never holds) and transitive; from an order ≤\leq one gets the strict order x<yx < y when x≤yx \leq y and x≠yx \neq y. An element mm of a subset SS is minimal in SS if no element of SS is smaller than mm. An immediate predecessor of yy is an x<yx < y with no zz such that x<z<yx < z < y.

Definition 11.9 (Well-founded order)

A strict order is well-founded if there is no infinite strictly descending chain x0>x1>x2>⋯x_0 > x_1 > x_2 > \cdots.

The natural numbers with << are well-founded; the integers are not (0>−1>−2>⋯0 > -1 > -2 > \cdots), nor the non-negative rationals (1>1/2>1/4>⋯1 > 1/2 > 1/4 > \cdots). Proper subtrees of a tree, or the order “is a proper subformula of”, are well-founded, since each step down a tree loses at least one node.

Proposition 11.10 (Two definitions agree)

A strict order is well-founded if and only if every non-empty subset has a minimal element.

Proof. If a non-empty set SS has no minimal element, pick x0x_0 in SS; it is not minimal, so some x1∈Sx_1 \in S is smaller; and so on, which builds an infinite descending chain. Conversely, an infinite descending chain is a non-empty set without minimal element: each of its elements has a smaller one after it. ∎

The second form gives well-founded induction: if P(y)P(y) follows from P(x)P(x) for all x<yx < y, then PP holds everywhere, for otherwise the set of counterexamples would have a minimal element yy, all of whose smaller elements satisfy PP, and so would yy. Induction on N\mathbb{N} and structural induction are the cases of << on numbers and of the “is a proper subtree of” order.

Definition 11.11 (Product order, lexicographic order)

On pairs of elements of ordered sets AA and BB, the product order sets (a,b)≤(a′,b′)(a, b) \leq (a', b') when a≤a′a \leq a' and b≤b′b \leq b'; the lexicographic order sets (a,b)<(a′,b′)(a, b) < (a', b') when a<a′a < a', or a=a′a = a' and b<b′b < b'. Both extend to tuples of a fixed length kk, the lexicographic order comparing the first component where two tuples differ.

Proposition 11.12 (Lexicographic order is well-founded)

If <A<_A and <B<_B are well-founded, the lexicographic order on A×BA \times B is well-founded, and so is the strict product order. By induction, so are both orders on kk-tuples.

Proof. Take a descending chain (a0,b0)>(a1,b1)>⋯(a_0, b_0) > (a_1, b_1) > \cdots. Along it, a0≥a1≥⋯a_0 \geq a_1 \geq \cdots, since each step either decreases aa or keeps it. As AA is well-founded, aa decreases only finitely many times: from some index on, aa is constant, and then bb decreases at every step, which can happen only finitely often in BB. So the chain is finite. A strict decrease in the product order is a decrease in the lexicographic order, so the product order has no infinite chain either. For kk-tuples, write A1×⋯×AkA_1 \times \dots \times A_k as A1×(A2×⋯×Ak)A_1 \times (A_2 \times \dots \times A_k). ∎

A descending chain in the lexicographic order on N2 from (4, 1). A step may jump upwards in j, without bound, but only by lowering i: the chain is finite, although no bound on its length can be given in advance.
A descending chain in the lexicographic order on N2\mathbb{N}^2 from (4,1)(4, 1). A step may jump upwards in jj, without bound, but only by lowering ii: the chain is finite, although no bound on its length can be given in advance.

The lexicographic order on N2\mathbb{N}^2 shows why well-foundedness is more than “the values stay positive”: the pair (1,0)(1, 0) has infinitely many smaller elements (0,j)(0, j), and no immediate predecessor, yet every descending chain is finite. A directed graph whose arcs all go from a larger to a smaller element has no cycle; the converse view, the order of reachability in a directed acyclic graph, returns with graphs in Chapter 24.

11.4 Termination by a variant

Definition 11.13 (Termination, variant)

A loop or a recursive function terminates if every execution reaches its end after finitely many steps. A variant is a function from the states of the loop (or the arguments of the function) to a set with a well-founded order that strictly decreases at each iteration (or at each recursive call). A loop with a variant terminates: otherwise the values of the variant would form an infinite descending chain.

Euclid’s algorithm, which replaces (a,b)(a, b) by (b,a mod b)(b, a \bmod b) while b>0b > 0, has the variant bb in N\mathbb{N}: a mod b<ba \bmod b < b. A variant need not be a number. The loop below has none in N\mathbb{N}, since it sometimes increases jj, but the pair (i,j)(i, j) decreases in the lexicographic order at every step.

i, j = 3, 0
steps = 0
while i > 0 or j > 0:
    print(f"step {steps:2d}: variant (i, j) = ({i}, {j})")
    if j > 0:
        j -= 1  # (i, j) > (i, j - 1)
    else:
        i, j = i - 1, 2 * i  # (i, 0) > (i - 1, anything): j may grow
    steps += 1
print(f"stopped after {steps} steps at ({i}, {j})")
Listing 11.3. A loop with a lexicographic variant code/bachelor-1/11-induction-and-termination/listings/lex_loop.py
$ python lex_loop.py
step  0: variant (i, j) = (3, 0)
step  1: variant (i, j) = (2, 6)
step  2: variant (i, j) = (2, 5)
step  3: variant (i, j) = (2, 4)
step 12: variant (i, j) = (1, 0)
step 13: variant (i, j) = (0, 2)
step 14: variant (i, j) = (0, 1)
stopped after 15 steps at (0, 0)
Output 11.3. The variant at each step (the middle steps are left out). Some lines are left out.

Ackermann’s function, named after the mathematician Wilhelm Ackermann, terminates for the same reason, although it calls itself on an argument that is the result of another call.

def ack(m, n):
    global calls
    calls += 1
    if m == 0:
        return n + 1
    if n == 0:
        return ack(m - 1, 1)
    return ack(m - 1, ack(m, n - 1))
Listing 11.4. Ackermann’s function code/bachelor-1/11-induction-and-termination/listings/ackermann.py
$ python ackermann.py
m\n             0             1             2             3             4
  0         1 (1)         2 (1)         3 (1)         4 (1)         5 (1)
  1         2 (2)         3 (4)         4 (6)         5 (8)        6 (10)
  2         3 (5)        5 (14)        7 (27)        9 (44)       11 (65)
  3        5 (15)      13 (106)      29 (541)     61 (2432)   125 (10307)
Output 11.4. Values, and calls in parentheses: the third row already doubles at each step.

Proposition 11.14 (Ackermann’s function terminates)

For all natural numbers mm and nn, the call ack(m,n)\mathit{ack}(m, n) terminates.

Proof. By well-founded induction on (m,n)(m, n) in the lexicographic order of N2\mathbb{N}^2. Suppose every call on a smaller pair terminates. If m=0m = 0, there is no call. If n=0n = 0, the call is on (m−1,1)<(m,0)(m - 1, 1) < (m, 0). Otherwise the inner call is on (m,n−1)<(m,n)(m, n - 1) < (m, n) and terminates with some value vv; the outer call is on (m−1,v)<(m,n)(m - 1, v) < (m, n), whatever vv is, and terminates. ∎

Termination says nothing about speed: ack(4,2)\mathit{ack}(4, 2) has 19 729 decimal digits, and its call count is beyond reach. The third row is 2n+3−32^{n + 3} - 3, which the test checks.

11.5 Recursive functions proved correct

def merge(xs, ys):
    if not xs:
        return ys
    if not ys:
        return xs
    if xs[0] <= ys[0]:
        return [xs[0]] + merge(xs[1:], ys)  # the variant drops by one
    return [ys[0]] + merge(xs, ys[1:])  # here too
Listing 11.5. Merging two sorted lists code/bachelor-1/11-induction-and-termination/listings/merge.py
$ python merge.py
[1, 2, 3, 4, 4, 4, 9, 10, 11]
[5, 6] [7]
Output 11.5. Two sorted lists merged, and the base cases.

Proposition 11.15 (Merge is correct)

If xsxs and ysys are sorted, merge(xs,ys)\mathit{merge}(xs, ys) terminates and returns a sorted list holding the elements of both, with their multiplicities.

Proof. Termination: len(xs)+len(ys)\text{len}(xs) + \text{len}(ys) is a variant, since each call removes one element. Correctness, by induction on the same quantity: if one list is empty, the other is returned, sorted. Otherwise, say xs[0]≤ys[0]xs[0] \leq ys[0]. By induction, the recursive call returns a sorted list of the elements of xs[1:]xs[1{:}] and ysys; each of them is at least xs[0]xs[0], since xsxs is sorted and ys[0]≥xs[0]ys[0] \geq xs[0]. Putting xs[0]xs[0] in front keeps the list sorted, and adds the one missing element. The other case is symmetric. ∎

Definition 11.16 (Left-child right-sibling representation)

The left-child right-sibling representation stores a tree of any arity as a binary tree with the same nodes: the left subtree of a node is its first child, and its right subtree is its next sibling.

class Tree:  # a node of any arity: a key and a list of children
    key: int
    children: list = field(default_factory=list)


def to_binary(t, siblings=()):
    """t and its younger siblings as one binary tree: left = first child of t,
    right = the next sibling of t."""
    first = to_binary(t.children[0], t.children[1:]) if t.children else None
    nxt = to_binary(siblings[0], siblings[1:]) if siblings else None
    return Node(first, t.key, nxt)


def from_binary(b):
    """The inverse: the list of trees that b and its right spine encode."""
    trees = []
    while b is not None:
        trees.append(Tree(b.key, from_binary(b.left)))
        b = b.right
    return trees


def show(b):
    return "." if b is None else f"({show(b.left)} {b.key} {show(b.right)})"
Listing 11.6. From any arity to binary, and back code/bachelor-1/11-induction-and-termination/listings/lcrs.py
$ python lcrs.py
binary tree: ((. 2 ((. 6 (. 7 .)) 3 (. 4 ((. 8 .) 5 .)))) 1 .)
back again equal: True
Output 11.6. The tree of the figure below as a binary tree (. is the empty tree), and the round trip.
A tree of arity 4 and its left-child right-sibling binary tree. The same eight nodes; the children of a node become a chain of right links starting at its left child.
A tree of arity 4 and its left-child right-sibling binary tree. The same eight nodes; the children of a node become a chain of right links starting at its left child.

The two conversions are inverse to each other, which is proved by structural induction on trees (and on lists of trees, the two definitions depending on each other); the test checks it on random trees. Mutually recursive functions, such as the even and odd test of Chapter 3, terminate by a common variant: here nn decreases at every call, whichever function makes it.

def is_even(n):
    return True if n == 0 else is_odd(n - 1)


def is_odd(n):
    return False if n == 0 else is_even(n - 1)


if __name__ == "__main__":
    print([n for n in range(12) if is_even(n)], is_odd(7))
Listing 11.7. Even and odd, in Python code/bachelor-1/11-induction-and-termination/listings/even_odd.py
$ python even_odd.py
[0, 2, 4, 6, 8, 10] True
Output 11.7. The even numbers below 12, and seven is odd.

11.6 Exercises

Exercise 11.1 ★

Give the size and height of: the empty tree; a single node; a node whose left subtree is a single node and right subtree empty; and the tree t of Output 11.1, Node(Node(None, 2, None), 5, Node(Node(None, 7, None), 9, None)).

Solution

Solution of Exercise 11.1.

Empty tree: size 0, height −1-1. Single node: 1 and 0. A node with a left child only: 2 and 1. The tree t: 4 nodes (5, 2, 9, 7), and the longest path 5, 9, 7 has two links: height 2, as Output 11.1 prints.

Exercise 11.2 ★

Euclid’s algorithm runs on (252,105)(252, 105). Give the successive values of the variant bb, and the result.

Solution

Solution of Exercise 11.2.

(252,105)→(105,42)→(42,21)→(21,0)(252, 105) \to (105, 42) \to (42, 21) \to (21, 0): the variant bb takes the values 105, 42, 21 and 0, and the result is 21.

Exercise 11.3 ★

Predict the output of the program.

from lcrs import Tree, show, to_binary

print(show(to_binary(Tree(1, [Tree(2, [Tree(4)]), Tree(3)]))))
print(show(to_binary(Tree(1, [Tree(2), Tree(3), Tree(4)]))))
Listing 11.8. Two small trees converted code/bachelor-1/11-induction-and-termination/listings/exo_lcrs.py
Solution

Solution of Exercise 11.3.

(((. 4 .) 2 (. 3 .)) 1 .)
((. 2 (. 3 (. 4 .))) 1 .)
Output 11.9. The two binary trees. Some lines are left out.

In the first tree, 2 is the first child of 1 (left of 1), 4 the first child of 2 (left of 2), and 3 the next sibling of 2 (right of 2). In the second, the three children of 1 form a chain of right links under the left child 2.

Exercise 11.4 ★

Which strict orders are well-founded? (a) << on the integers greater than −10-10; (b) “divides and is different” on positive integers; (c) “is a proper prefix of” on finite words; (d) << on the real numbers of [0,1][0, 1].

Solution

Solution of Exercise 11.4.

(a) Well-founded: a descending chain of integers greater than −10-10 starting at x0x_0 has at most x0+10x_0 + 10 steps. (b) Well-founded: a proper divisor of a positive integer is smaller than it, so a descending chain is a descending chain in N\mathbb{N}. (c) Well-founded: a proper prefix is shorter. (d) Not well-founded: 1>1/2>1/4>⋯1 > 1/2 > 1/4 > \cdots.

Exercise 11.5 ★★

A student claims that nn is a variant of steps. Show that it is not, prove that the function terminates for all natural numbers nn and step∈{0,1}\mathit{step} \in \{0, 1\} with a lexicographic variant, and give its result.

def steps(n, step):
    print(f"steps({n}, {step})")
    if n <= 0:
        return 0
    if step == 0:
        return steps(n, 1)  # start moving
    return 1 + steps(n - step, step)


print("result", steps(3, 0))
Listing 11.9. A recursion with two kinds of call code/bachelor-1/11-induction-and-termination/listings/exo_variant.py
Solution

Solution of Exercise 11.5.

steps(3, 0)
steps(3, 1)
steps(2, 1)
steps(1, 1)
steps(0, 1)
result 3
Output 11.10. The calls. Some lines are left out.

The call steps(n, 1) made from steps(n, 0) keeps nn: nn is not a variant. The pair (n,1−step)(n, 1 - \mathit{step}) is one, in the lexicographic order of N2\mathbb{N}^2: from (n,1)(n, 1) to (n,0)(n, 0) on the first kind of call, from (n,0)(n, 0) to (n−1,0)(n - 1, 0) on the second. By induction along this order, steps(n, step) returns nn for every natural number nn.

Exercise 11.6 ★★

A library defines the height of the empty tree as 0. Which statements of Proposition 11.7 fail with that convention, and how must they be rewritten?

def height0(t):
    return 0 if t is None else 1 + max(height0(t.left), height0(t.right))


leaf = Node(None, 1, None)
for name, t in [("empty", None), ("leaf", leaf), ("three nodes", Node(leaf, 2, leaf))]:
    h = height0(t)
    print(f"{name:12} height0 {h}  size {size(t)}  size <= 2^(h+1) - 1: "
          f"{size(t) <= 2 ** (h + 1) - 1}  size >= h + 1: {size(t) >= h + 1}")
Listing 11.10. Another height code/bachelor-1/11-induction-and-termination/listings/exo_height0.py
Solution

Solution of Exercise 11.6.

empty        height0 0  size 0  size <= 2^(h+1) - 1: True  size >= h + 1: False
leaf         height0 1  size 1  size <= 2^(h+1) - 1: True  size >= h + 1: False
three nodes  height0 2  size 3  size <= 2^(h+1) - 1: True  size >= h + 1: True
Output 11.11. The two conventions compared. Some lines are left out.

With that convention every height is one more, h′=h+1h' = h + 1. The bound n≤2h+1−1n \leq 2^{h + 1} - 1 still holds but is no longer reached; n≥h+1n \geq h + 1 fails, for the empty tree and for a single node. Rewritten: h′≤n≤2h′−1h' \leq n \leq 2^{h'} - 1, and at most 2h′−12^{h' - 1} leaves (Exercise 11.9).

Exercise 11.7 ★★

Write count_paths(t), the number of paths from the root of a binary tree to a leaf, by recursion on the tree. Prove by structural induction that it equals the number of leaves, and give its value on a full tree with ii internal nodes.

Solution

Solution of Exercise 11.7.

def count_paths(t):
    if t is None:
        return 0
    if t.left is None and t.right is None:
        return 1  # the path made of the leaf alone
    return count_paths(t.left) + count_paths(t.right)
Paths from the root to a leaf code/bachelor-1/11-induction-and-termination/exercises/count_paths.py

By structural induction: the empty tree has no path and no leaf; a single node has one path and one leaf; otherwise a path from the root to a leaf goes into exactly one of the two subtrees, and continues as a path from the root of that subtree to a leaf of it, so the counts add, as the leaves do. On a full tree with ii internal nodes there are i+1i + 1 leaves (Proposition 11.7), hence i+1i + 1 paths. The test tests/test_trees.py checks both on random trees.

Exercise 11.8 ★★

With flatten(empty)=[ ]\mathit{flatten}(\text{empty}) = [\,] and flatten((ℓ,k,r))=flatten(ℓ)+[k]+flatten(r)\mathit{flatten}((\ell, k, r)) = \mathit{flatten}(\ell) + [k] + \mathit{flatten}(r), prove len(flatten(t))=size(t)\text{len}(\mathit{flatten}(t)) = \text{size}(t) by structural induction.

Solution

Solution of Exercise 11.8.

Empty tree: len([ ])=0=size\text{len}([\,]) = 0 = \text{size}. Node (ℓ,k,r)(\ell, k, r): len(flatten(ℓ)+[k]+flatten(r))=len(flatten(ℓ))+1+len(flatten(r))=size(ℓ)+1+size(r)\text{len}(\mathit{flatten}(\ell) + [k] + \mathit{flatten}(r)) = \text{len}(\mathit{flatten}(\ell)) + 1 + \text{len}(\mathit{flatten}(r)) = \text{size}(\ell) + 1 + \text{size}(r) by the induction hypothesis, which is the size of the node.

Exercise 11.9 ★★

Prove that a non-empty binary tree of height hh has at most 2h2^h leaves. Which trees reach the bound?

Solution

Solution of Exercise 11.9.

By structural induction on non-empty trees. A single node: height 0, one leaf, 20=12^0 = 1. A node with one empty subtree: its leaves are those of the other subtree, of height h−1h - 1, so at most 2h−1≤2h2^{h - 1} \leq 2^h. A node with two non-empty subtrees of heights at most h−1h - 1: at most 2h−1+2h−1=2h2^{h - 1} + 2^{h - 1} = 2^h leaves. The bound is reached exactly by the perfect trees, in which every internal node has two children and every leaf has depth hh.

Exercise 11.10 ★★★

On the finite words over a finite alphabet, the shortlex order compares lengths first and, between words of the same length, uses the dictionary order. Prove that it is well-founded. Show that the dictionary order alone, on the words over {a,b}\{a, b\}, is not.

Solution

Solution of Exercise 11.10.

In a descending chain for shortlex, the lengths never increase, so from some point on they are constant, equal to some LL (lengths are natural numbers). From then on the chain is strictly descending among the words of length LL, of which there are finitely many: it is finite. For the dictionary order, b>ab>aab>aaab>⋯b > ab > aab > aaab > \cdots: at each step the first letters compare a<ba < b at the first difference, and the chain never ends.

Exercise 11.11 ★★★

In the sorting game, a move swaps two adjacent numbers of a list that are out of order. Prove that every game ends, with a variant, that it ends on the sorted list, and that the number of moves does not depend on the choices. Write the game and test the claims.

Solution

Solution of Exercise 11.11.

"""sort_game.py: swap two adjacent numbers that are out of order, until none is.

The variant is the number of inversions, pairs i < j with xs[i] > xs[j]: a swap
of an adjacent inverted pair removes exactly that inversion and changes no other."""


def inversions(xs):
    return sum(xs[i] > xs[j] for i in range(len(xs)) for j in range(i + 1, len(xs)))


def play(xs, choose=min):
    """Play until sorted; choose picks among the positions of inverted pairs."""
    xs, moves = list(xs), 0
    while True:
        out_of_order = [i for i in range(len(xs) - 1) if xs[i] > xs[i + 1]]
        if not out_of_order:
            return xs, moves
        i = choose(out_of_order)
        xs[i], xs[i + 1] = xs[i + 1], xs[i]
        moves += 1
The sorting game code/bachelor-1/11-induction-and-termination/exercises/sort_game.py

A swap of an adjacent inverted pair xi>xi+1x_i > x_{i+1} removes that inversion; every other pair keeps its two elements, in the same order, so the number of inversions decreases by exactly one. It is a variant in N\mathbb{N}, so every game ends. It ends when no adjacent pair is inverted, that is when the list is sorted; and it takes exactly as many moves as the starting list has inversions, whatever the choices. The test plays with the leftmost and the rightmost choice and checks the result and the count on random lists.

Exercise 11.12 ★★★

McCarthy’s 91 function is f(n)=n−10f(n) = n - 10 if n>100n > 100, and f(n)=f(f(n+11))f(n) = f(f(n + 11)) otherwise. Prove that f(n)=91f(n) = 91 for every integer n≤100n \leq 100, by well-founded induction on 101−n101 - n (with a separate argument for 90≤n≤10090 \leq n \leq 100), and deduce that ff terminates on every integer.

Solution

Solution of Exercise 11.12.

Use well-founded induction on m=101−n≥1m = 101 - n \geq 1 for n≤100n \leq 100, proving that f(n)f(n) terminates with value 91. First, if 90≤n≤10090 \leq n \leq 100, then n+11>100n + 11 > 100, so f(n+11)=n+1f(n + 11) = n + 1 and f(n)=f(n+1)f(n) = f(n + 1); with f(101)=91f(101) = 91, going down from 100 to 90 gives f(n)=91f(n) = 91. If n<90n < 90, then n+11≤100n + 11 \leq 100 and 101−(n+11)<m101 - (n + 11) < m, so by induction f(n+11)f(n + 11) terminates with 91, and f(n)=f(91)=91f(n) = f(91) = 91 by the first case. For n>100n > 100 the function returns at once. The test checks the values from −50-50 to 200.

11.7 Problem: The game that always ends

Problem 11.1

Weekend problem — The game that always ends

A position is a list of natural numbers. A move picks an entry k>0k > 0 and replaces it by two entries k−1k - 1; the play ends when every entry is 0. From (2)(2) one may play (2)→(1,1)→(0,0,1)→(0,0,0,0)(2) \to (1, 1) \to (0, 0, 1) \to (0, 0, 0, 0), or replace the other 1 first. The program lists the possible lengths of all plays from a few positions, and counts the plays.

def moves(state):
    """Every state one move away; a state is a tuple of natural numbers."""
    return [state[:i] + (k - 1, k - 1) + state[i + 1:]
            for i, k in enumerate(state) if k > 0]


@cache
def lengths(state):
    """The set of lengths of all plays from state."""
    nxt = moves(state)
    if not nxt:
        return frozenset([0])
    return frozenset(1 + n for s in nxt for n in lengths(s))


@cache
def plays(state):
    """The number of different plays from state."""
    nxt = moves(state)
    return 1 if not nxt else sum(plays(s) for s in nxt)


def potential(state):
    return sum(2 ** a - 1 for a in state)
Listing 11.11. The game, its plays and their lengths code/bachelor-1/11-induction-and-termination/listings/game.py
$ python game.py
start        potential  play lengths        plays
(1,)                 1           [1]            1
(2,)                 3           [3]            2
(3,)                 7           [7]           80
(4,)                15          [15]     21964800
(1, 2)               4           [4]            8
(2, 2, 1)            7           [7]          560
(3, 1, 0)            8           [8]          640
(3, 3)              14          [14]     21964800
Output 11.8. One length per position, whatever the choices, among up to 21 964 800 different plays.

Part I — Positions and plays as data.

  1. Define the set of plays inductively: a play from a position ss is either ss alone, if no move is possible, or ss followed by a play from a position one move away.
  2. List the two plays from (2)(2) and the two from (1,1)(1, 1).
  3. Why does plays((4,)) equal plays((3, 3))?
  4. Explain the recursion of lengths, and why its base case returns {0}\{0\}.
  5. Why is @cache needed to count 21 964 800 plays?
  6. Does the order of the entries in a position matter for the lengths? For the number of plays?

Part II — Termination.

  1. Show that the sum of the entries is not a variant, nor the number of entries, nor the largest entry.
  2. Let KK be the largest entry of the starting position. Show that no entry ever exceeds KK.
  3. For a position ss, let c(s)=(cK,cK−1,…,c0)c(s) = (c_K, c_{K-1}, \dots, c_0), where cjc_j is the number of entries equal to jj. Show that a move decreases c(s)c(s) in the lexicographic order of NK+1\mathbb{N}^{K+1}.
  4. Deduce from Proposition 11.12 that every play is finite.
  5. Is cc a variant in the product order? Why does that not matter?
  6. Could a play from (3,1,0)(3, 1, 0) be longer than 1000 moves? Answer from Part II alone, then from the table.

Part III — A single entry.

  1. Let M(k)M(k) be the number of moves of a play from (k)(k), assuming it does not depend on the choices. Show M(0)=0M(0) = 0 and M(k)=1+2M(k−1)M(k) = 1 + 2M(k - 1).
  2. Deduce M(k)=2k−1M(k) = 2^k - 1 by induction, and compare with the table.
  3. In a play from (k)(k), the two copies of k−1k - 1 evolve independently. Make this precise: a play from a position is an interleaving of plays from its entries.
  4. Deduce that a play from (a1,…,an)(a_1, \dots, a_n) makes ∑i(2ai−1)\sum_i (2^{a_i} - 1) moves, if each single-entry play has a fixed length.
  5. Where did Part III assume what it set out to prove? Why does the interleaving argument still need the single-entry result as an induction hypothesis?
  6. Give the number of plays from (2)(2), (3)(3) and (1,2)(1, 2) from the table, and check (2)(2) and (1,2)(1, 2) by hand.

Part IV — A potential.

  1. Let Φ(s)=∑i(2ai−1)\Phi(s) = \sum_i (2^{a_i} - 1). Compute the change of Φ\Phi in a move that replaces kk by two copies of k−1k - 1.
  2. Show that Φ(s)≥0\Phi(s) \geq 0, with equality exactly when the play has ended.
  3. Deduce that every play from ss has exactly Φ(s)\Phi(s) moves.
  4. Compare this proof with that of Part II: which one gives termination, which one the length, and why is Φ\Phi a variant in N\mathbb{N} although the sum of entries was not?
  5. The program checks the result on every position of at most three entries below 4. What does that check add to the proof, and what does the proof add to the check?
  6. State the named result: every play from (a1,…,an)(a_1, \dots, a_n) has the same length ∑i(2ai−1)\sum_i (2^{a_i} - 1).
Solution

Solution of Problem 11.1.

1. The base rule: a position with no entry above 0 is a play by itself. The construction rule: if s′s' is one move away from ss and pp is a play from s′s', then ss followed by pp is a play from ss.

2. From (2)(2): (2),(1,1),(0,0,1),(0,0,0,0)(2), (1, 1), (0, 0, 1), (0, 0, 0, 0) and (2),(1,1),(1,0,0),(0,0,0,0)(2), (1, 1), (1, 0, 0), (0, 0, 0, 0). From (1,1)(1, 1): the same two without their first position.

3. The only move from (4)(4) leads to (3,3)(3, 3), so every play from (4)(4) is (4)(4) followed by a play from (3,3)(3, 3).

4. It follows the inductive definition of plays: a final position has one play, of length 0; otherwise the lengths are one more than those of the plays from each position one move away.

5. The same position is reached by many orders of moves; without the cache, plays would recompute it each time, and the count would cost as many calls as there are plays, 21 964 800. With the cache, each position is computed once.

6. No: exchanging entries exchanges the moves, and gives a one-to-one correspondence between the plays of the two positions, which preserves lengths. The number of plays is the same too.

7. The sum changes by 2(k−1)−k=k−22(k - 1) - k = k - 2, which is positive for k≥3k \geq 3: (3)→(2,2)(3) \to (2, 2) raises it from 3 to 4. The number of entries grows by one at each move. The largest entry can stay the same: (2,2)→(1,1,2)(2, 2) \to (1, 1, 2).

8. A move adds only entries k−1k - 1, smaller than an existing entry.

9. The move lowers ckc_k by one and raises ck−1c_{k - 1} by two, leaving the others. The first component where the vectors differ is ckc_k, which decreased.

10. The lexicographic order on NK+1\mathbb{N}^{K + 1} is well-founded, and a play gives a descending chain of vectors c(s)c(s): it is finite.

11. No: ck−1c_{k - 1} increases, so the new vector is not below the old in the product order. Only the existence of a well-founded order in which cc decreases matters.

12. Part II proves that every play is finite but gives no bound: a lexicographic chain can be as long as one likes. The table says that every play from (3,1,0)(3, 1, 0) has 8 moves.

13. From (0)(0) no move is possible. From (k)(k) the first move gives (k−1,k−1)(k - 1, k - 1), and each copy then needs M(k−1)M(k - 1) moves of its own: M(k)=1+2M(k−1)M(k) = 1 + 2M(k - 1).

14. M(0)=0=20−1M(0) = 0 = 2^0 - 1, and 1+2(2k−1−1)=2k−11 + 2(2^{k - 1} - 1) = 2^k - 1. The table: 1, 3, 7, 15 for k=1,…,4k = 1, \dots, 4.

15. Each move acts on one entry, and the entries it creates descend from it. Restricted to the descendants of entry ii, the moves of a play form a play from (ai)(a_i), and the whole play interleaves these nn plays.

16. The moves of the whole play are the moves of the nn sub-plays: ∑iM(ai)=∑i(2ai−1)\sum_i M(a_i) = \sum_i (2^{a_i} - 1).

17. Question 13 assumed that M(k−1)M(k - 1) is well defined. The proof is an induction on kk: assuming every play from (k−1)(k - 1) has 2k−1−12^{k - 1} - 1 moves, question 15 applied to (k−1,k−1)(k - 1, k - 1) shows that every play from (k)(k) has 1+2(2k−1−1)1 + 2(2^{k - 1} - 1) moves.

18. 2, 80 and 8. From (1,2)(1, 2): the play from (2)(2) has 3 moves, in 2 orders, and the single move of (1)(1) can come in any of 4 places among them: 4×2=84 \times 2 = 8.

19. −(2k−1)+2(2k−1−1)=−2k+1+2k−2=−1-(2^k - 1) + 2(2^{k - 1} - 1) = -2^k + 1 + 2^k - 2 = -1.

20. Each term 2ai−12^{a_i} - 1 is at least 0, and 0 only for ai=0a_i = 0; so Φ(s)=0\Phi(s) = 0 exactly when every entry is 0, when no move is possible.

21. Each move lowers Φ\Phi by exactly one, and the play ends exactly when Φ\Phi reaches 0: a play from ss has Φ(s)\Phi(s) moves, which also proves termination again.

22. Part II gives termination and nothing more; Φ\Phi gives both, because it decreases by exactly one. The sum weighs an entry kk by kk, less than the two entries k−1k - 1 can weigh; Φ\Phi weighs it by 2k−12^k - 1, exactly the cost of the play it will start, so that the move pays one and leaves the rest to the copies.

23. The check covers 84 positions exhaustively, and would have caught an error in the program, or a wrong formula; the proof covers every position, of any length and any entries, which no check can enumerate.

24. Every play from (a1,…,an)(a_1, \dots, a_n) has the same length ∑i(2ai−1)\sum_i (2^{a_i} - 1): each move lowers the potential Φ\Phi by exactly one, and the play ends exactly when Φ\Phi is 0. The table and the test confirm it on all the positions they try, from (1)(1) with 1 move to (4)(4) and (3,3)(3, 3), whose 21 964 800 plays all have 15 and 14 moves.

本章定义的术语

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