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

High School Computer Science

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

High School Computer Science · 10–12 年级

20Modules, Interfaces and Libraries

Twenty programs of the town hall use the same small module of dates: the school calendar, the library’s loans, the market’s opening days. One summer the module is rewritten and becomes thousands of times faster on large calendars. None of the twenty programs is changed, none of them breaks, and their authors only notice that things run faster.

That is possible because the twenty programs relied only on what the module promised, never on how it kept its dates. This chapter splits programs into modules, separates the promise from the way it is kept, reads the documentation of Python’s own modules, and then changes an implementation behind its users’ backs, with the tests to prove nothing broke.

You already know

A function has parameters and returns a value (the first book of the series). A specification states what a function must do, and tests check it (chapter 1); a set answers x in s without a scan (chapter 2); the number of halvings h(n)h(n) and the cost of searching (chapter 17).

20.1 Splitting a program into modules

Definition 20.1 (Module)

A module is a file of code whose names, functions, constants and others, other programs can use by importing it. In Python every file name.py is a module named name.

"""Points of the plane as pairs (x, y): distances and perimeters."""
import math


def _square(v):
    return v * v


def distance(p, q):
    """Return the distance between the points p and q."""
    return math.sqrt(_square(p[0] - q[0]) + _square(p[1] - q[1]))


def perimeter(points):
    """Return the length of the closed path through points, in order.

    points is a list of at least two pairs (x, y); the path goes back
    from the last point to the first.
    """
    total = 0.0
    for i in range(len(points)):
        total += distance(points[i], points[(i + 1) % len(points)])
    return total
Listing 20.1. A module of plane geometry: two functions and a helper. code/grade-11/09-modules-and-interfaces/listings/geometry.py

import geometry runs the file once and makes the single name geometry available; its contents are reached through it, as geometry.distance. from geometry import perimeter copies one name into the program, to be used without the prefix.

import geometry
from geometry import perimeter

square = [(0, 0), (3, 0), (3, 3), (0, 3)]
print(geometry.distance((0, 0), (3, 4)))
print(perimeter(square))
print("module:", geometry.__name__, "| this program:", __name__)
print("names in geometry:", [n for n in dir(geometry) if not n.startswith("__")])
Listing 20.2. Two ways of importing, and the names a module holds. code/grade-11/09-modules-and-interfaces/listings/use_geometry.py
$ python use_geometry.py
5.0
12.0
module: geometry | this program: __main__
names in geometry: ['_square', 'distance', 'math', 'perimeter']
Output 20.1. The module also holds math, which it imported for itself, and the helper _square.

Python looks for a module first in the directory of the program being run, then in the directories listed in the variable PYTHONPATH, then where the installation keeps its modules; the list is in sys.path. A module named like one of Python’s own, random.py next to a program, hides the real one: a classic trap.

Each module has a name in the variable __name__. A file started as a program gets the name "__main__"; imported, it gets its own name. The guard if __name__ == "__main__": keeps a demonstration from running when the file is only imported.

"""Greets only when started as a program, not when imported."""


def greet(name):
    return f"hello, {name}"


print("main_guard is running as", __name__)
if __name__ == "__main__":
    print(greet("ada"))
Listing 20.3. A module with a guarded demonstration. code/grade-11/09-modules-and-interfaces/listings/main_guard.py
$ python main_guard.py
main_guard is running as __main__
hello, ada
Output 20.2. Started as a program: the guard lets the greeting through.
$ python import_guard.py
main_guard is running as main_guard
hello, Brenmoor
Output 20.3. Imported by import_guard.py, which calls greet itself: the module’s own greeting does not run.

A module’s statements run only at its first import; a second import in the same run finds it already loaded.

The modules of this chapter’s date programs. An arrow goes from a module to a module it imports; the grey ones come with Python.
The modules of this chapter’s date programs. An arrow goes from a module to a module it imports; the grey ones come with Python.

20.2 The interface and the hidden implementation

Definition 20.2 (Interface, implementation)

The interface of a module is what its users may rely on: the names it offers and, for each, a specification. The implementation is the code that keeps these promises, and everything else in the module: helpers, data structures, imported modules.

Python does not lock anything away: geometry._square can be called. The protection is a convention: a name beginning with an underscore is internal, and from geometry import * does not even copy it. A name that is not documented, or that the module only imported for itself, as geometry.math, is internal too.

The documentation of a function is its docstring, which help prints.

import geometry

help(geometry.perimeter)
Listing 20.4. Asking for the documentation of a function. code/grade-11/09-modules-and-interfaces/listings/help_view.py
$ python help_view.py
Help on function perimeter in module geometry:

perimeter(points)
    Return the length of the closed path through points, in order.

    points is a list of at least two pairs (x, y); the path goes back
    from the last point to the first.
Output 20.4. The signature and the docstring: all a user needs.
The interface as a wall. Above it, five names with their specifications, the same in the three modules; below it, three ways of keeping the dates, which users never see.
The interface as a wall. Above it, five names with their specifications, the same in the three modules; below it, three ways of keeping the dates, which users never see.

20.3 The standard library and its documentation

Definition 20.3 (Library, standard library)

A library is a collection of modules written to be used by other programs. The standard library of a language is the library that comes with every installation of it.

Definition 20.4 (API)

The API, for application programming interface, of a library is its interface: the names, with their specifications, that programs may use.

Python’s standard library has hundreds of modules, and its documentation describes each function in a fixed shape: the signature, what it returns, what it raises and when, examples, and in which version it changed.

The parts of a documentation entry, on the entry for statistics.median, shortened. Reading the raised exceptions and the examples is part of reading the entry.
The parts of a documentation entry, on the entry for statistics.median, shortened. Reading the raised exceptions and the examples is part of reading the entry.
import random
import statistics
from collections import Counter
from datetime import date, timedelta

rng = random.Random(7)
print(rng.choice(["letter", "packet", "parcel"]))
print(statistics.median([3, 1, 4, 1, 5, 9]), statistics.median([3, 1, 4]))
print(Counter("abracadabra").most_common(3))
d = date.fromisoformat("2026-11-20")
print(d, d.weekday(), d + timedelta(days=100), date(2027, 1, 1) - d)
Listing 20.5. Four modules of the standard library, used after reading their entries. code/grade-11/09-modules-and-interfaces/listings/stdlib_tour.py
$ python stdlib_tour.py
packet
3.5 3
[('a', 5), ('b', 2), ('r', 2)]
2026-11-20 4 2027-02-28 42 days, 0:00:00
Output 20.5. A choice, two medians, the three most common letters, and some dates.

Each line of the output is explained by an entry:

  • random.choice returns an element of a non-empty sequence, and raises IndexError on an empty one. The documentation also warns that, for a given seed, only random() itself is guaranteed to give the same numbers in every version of Python; choice may change.
  • statistics.median of an even number of values is the mean of the two middle ones, here (3+4)/2(3 + 4) / 2.
  • Counter.most_common lists equal counts in the order first met: b before r.
  • date.weekday() numbers Monday 00 to Sunday 66: 44 is a Friday. Subtracting two dates gives a timedelta, here 4242 days; years run from 11 to 99999999.

Remark 20.5

The documentation is written for one version of Python. The entries of this book were read for version 3.123.12; an entry that says “changed in version” or “new in version” tells what an older or newer Python does differently.

20.4 Changing an implementation without touching its users

The module of dates of the town hall, met at the start of the chapter, offers five functions. Its first implementation keeps the dates in a list.

"""A set of dates, kept in a list.

Interface: empty(), from_dates(dates), add(s, d), contains(s, d), size(s).
"""


def empty():
    """Return a new set of dates, with no date in it."""
    return []


def from_dates(dates):
    """Return a new set holding the dates of the iterable dates."""
    return list(dict.fromkeys(dates))


def add(s, d):
    """Add the date d to s; nothing changes if d is already in s."""
    if d not in s:
        s.append(d)


def contains(s, d):
    """Return True when the date d is in s."""
    return d in s


def size(s):
    """Return the number of dates in s."""
    return len(s)
Listing 20.6. A set of dates kept in a list. code/grade-11/09-modules-and-interfaces/listings/dateset_list.py

The second keeps them in a Python set; only the bodies change, and they become shorter.

def empty():
    """Return a new set of dates, with no date in it."""
    return set()


def from_dates(dates):
    """Return a new set holding the dates of the iterable dates."""
    return set(dates)


def add(s, d):
    """Add the date d to s; nothing changes if d is already in s."""
    s.add(d)


def contains(s, d):
    """Return True when the date d is in s."""
    return d in s


def size(s):
    """Return the number of dates in s."""
    return len(s)
Listing 20.7. The same interface, kept in a set (lines 1–4, the module’s docstring, are not shown). code/grade-11/09-modules-and-interfaces/listings/dateset_set.py
from datetime import date

import dateset_list
import dateset_set

for ds in [dateset_list, dateset_set]:
    holidays = ds.empty()
    for text in ["2026-01-01", "2026-05-01", "2026-12-25", "2026-05-01"]:
        ds.add(holidays, date.fromisoformat(text))
    print(ds.__name__, "size", ds.size(holidays),
          "| 25 December:", ds.contains(holidays, date(2026, 12, 25)),
          "| 24 December:", ds.contains(holidays, date(2026, 12, 24)))
Listing 20.8. A user of the interface, run with each implementation. code/grade-11/09-modules-and-interfaces/listings/use_dateset.py
$ python use_dateset.py
dateset_list size 3 | 25 December: True | 24 December: False
dateset_set size 3 | 25 December: True | 24 December: False
Output 20.6. The same answers from both: the second 1 May was not added twice.

The tests are written against the interface only, and the same file tests every implementation, named on the command line.

"""The tests of the interface: python dateset_tests.py list|set|sorted."""
import importlib
import sys
import unittest
from datetime import date

name = sys.argv.pop(1) if len(sys.argv) > 1 else "list"
ds = importlib.import_module("dateset_" + name)
NEW_YEAR, LABOUR_DAY = date(2026, 1, 1), date(2026, 5, 1)


class DatesetTests(unittest.TestCase):
    def test_empty(self):
        s = ds.empty()
        self.assertEqual(ds.size(s), 0)
        self.assertFalse(ds.contains(s, NEW_YEAR))

    def test_add_twice(self):
        s = ds.empty()
        ds.add(s, NEW_YEAR)
        ds.add(s, NEW_YEAR)
        self.assertEqual(ds.size(s), 1)

    def test_contains(self):
        s = ds.from_dates([LABOUR_DAY, NEW_YEAR, LABOUR_DAY])
        self.assertTrue(ds.contains(s, NEW_YEAR))
        self.assertFalse(ds.contains(s, date(2026, 1, 2)))
        self.assertEqual(ds.size(s), 2)


if __name__ == "__main__":
    print("implementation:", ds.__name__, flush=True)
    unittest.main(verbosity=2)
Listing 20.9. The tests of the interface: one file for every implementation. code/grade-11/09-modules-and-interfaces/listings/dateset_tests.py
$ python dateset_tests.py list 2>&1 | grep -v '^Ran '
implementation: dateset_list
test_add_twice (__main__.DatesetTests.test_add_twice) ... ok
test_contains (__main__.DatesetTests.test_contains) ... ok
test_empty (__main__.DatesetTests.test_empty) ... ok

----------------------------------------------------------------------

OK
$ python dateset_tests.py set 2>&1 | grep -v '^Ran '
implementation: dateset_set
test_add_twice (__main__.DatesetTests.test_add_twice) ... ok
test_contains (__main__.DatesetTests.test_contains) ... ok
test_empty (__main__.DatesetTests.test_empty) ... ok

----------------------------------------------------------------------

OK
Output 20.7. The same three tests pass on both implementations (the line with the running time is filtered out).

Method 20.6 (Changing an implementation safely)

  1. Write the interface down: the names and the specification of each, in docstrings.
  2. Write tests that use the interface only, and check that they pass on the old implementation.
  3. Write the new implementation with the same names and specifications.
  4. Run the same tests on it. Users need change nothing but, at most, the name of the module they import.

20.5 Libraries outside the standard library, and what languages share

In practice — Libraries from elsewhere

Thousands of libraries are published outside the standard library. Python’s installer, pip, fetches them from a public index; other languages have their own installers. Before relying on one, a programmer checks its version (an update may change the interface), its licence (what it allows), and whether it is still maintained. This book installs nothing: every program in it uses the standard library only.

Languages differ in their spelling, much less in their constructions. The same few constructions appear in the toy machine’s assembly language of chapter 13 and in Python:

constructiontoy assemblyPython
assignmentLOADI R0, 3r0 = 3
sequenceone instruction after anotherone line after another
conditionalCMP then JC to a labelif a < b:
loopJNZ loop back to a labelwhile r0 != 0:
callCALL square, RETsquare(x), return

A compiler or an interpreter translates the right-hand column into something like the middle one.

20.6 Exercises

Exercise 20.1 ★

After import geometry alone, which of these work: geometry.distance((0, 0), (1, 1)), distance((0, 0), (1, 1)), geometry.math.sqrt(4)? Which should a user avoid, even if it works?

Solution

Solution of Exercise 20.1.

geometry.distance((0, 0), (1, 1)) works and returns 2\sqrt{2}. distance(...) raises NameError: import geometry makes only the name geometry available. geometry.math.sqrt(4) works and returns 2.0, but math is a module that geometry imported for itself, an implementation detail: a user imports math directly.

Exercise 20.2 ★

The file report.py holds the line print(__name__). The file main.py holds import report then print(__name__). What does python main.py print? And python report.py?

Solution

Solution of Exercise 20.2.

Running main.py prints report, when the import runs report.py, and then __main__. Running report.py as a program prints __main__.

Exercise 20.3 ★

A module defines MAX_SIZE, _cache, load, _parse and save, and imports json. Which names belong to its interface?

Solution

Solution of Exercise 20.3.

MAX_SIZE, load and save, provided they are documented. _cache and _parse are internal by their underscore; json is a module imported for the module’s own use.

Exercise 20.4 ★

From the entries quoted in the chapter, give without running them statistics.median([7, 1, 3, 9]) and Counter("banana").most_common(2).

Solution

Solution of Exercise 20.4.

Sorted, the values are 1,3,7,91, 3, 7, 9; an even count gives the mean of the two middle ones: 5.0. [('a', 3), ('n', 2)]: three a, two n, one b.

Exercise 20.5 ★

Write a module temperature with two functions, to_fahrenheit(c) and to_celsius(f), each with a docstring. (Fahrenheit is Celsius times 9/59/5, plus 3232.)

Solution

Solution of Exercise 20.5.

In temperature.py:

def to_fahrenheit(c):

"""Return the temperature c, in degrees Celsius, in degrees Fahrenheit."""

return c * 9 / 5 + 32

def to_celsius(f):

"""Return the temperature f, in degrees Fahrenheit, in degrees Celsius."""

return (f - 32) * 5 / 9

The tests check 100100 against 212212 and that −40-40 is the same on both scales.

Exercise 20.6 ★★

stops.py starts with import lines, defines FIRST_STOP = "Market Square", then prints lines.LINES[0]; lines.py starts with import stops and defines LINES from stops.FIRST_STOP. python stops.py stops with AttributeError: partially initialized module 'lines' has no attribute 'LINES'. Explain, and correct.

Solution

Solution of Exercise 20.6.

python stops.py runs stops.py as __main__. Its first line starts loading lines, whose first line imports stops: a second module, made from the same file. That one imports lines, which is already being loaded and is returned as it is, without LINES yet; it then defines FIRST_STOP and reads lines.LINES: the error. Two modules that each need the other at import time form a cycle. Correction: put FIRST_STOP in a third module, places.py, which both import, and which imports neither.

Exercise 20.7 ★★

A program does holidays = dateset_list.from_dates(days), then holidays.sort() and prints holidays[0], the earliest holiday. It breaks when the town switches to dateset_set. Whose fault is it, and how should the earliest date be obtained?

Solution

Solution of Exercise 20.7.

The user’s: the interface never promised a list, and sort and [0] rely on the implementation. The set has no sort and no index. The right way is to ask the module’s author for a function in the interface, such as earliest(s), implemented by each version (min(s) for the list and the set, s[0] for the sorted list).

Exercise 20.8 ★★

Rewrite geometry.perimeter without indices, with zip, so that the same tests still pass.

Solution

Solution of Exercise 20.8.

def perimeter(points):

pairs = zip(points, points[1:] + points[:1])

return sum(distance(p, q) for p, q in pairs)

points[1:] + points[:1] is the list shifted by one place, the first point moved to the end: zip pairs each point with the next, and the last with the first. The tests compare it with the original on 100100 random polygons.

Exercise 20.9 ★★

For nn dates, how many dates do add and contains look at, at most, in dateset_list? What about dateset_set?

Solution

Solution of Exercise 20.9.

In dateset_list, contains compares with up to nn dates, and add too, since it first checks that the date is absent. In dateset_set, both compute where the date is stored, and look at about one date, whatever nn (chapter 17).

Exercise 20.10 ★★

What does this print, and why? print(pow(2, 10)), then from math import *, then again print(pow(2, 10)).

Solution

Solution of Exercise 20.10.

1024, then 1024.0. from math import * copies all of math’s public names, among them math.pow, which replaces the built-in pow; math.pow converts its arguments to float. The import changed the meaning of a name the program already used.

Exercise 20.11 ★★

After reading the entry for Counter, write word_count(text, n), which returns the n most common words of a text in lower case, with their counts, punctuation removed.

Solution

Solution of Exercise 20.11.

def word_count(text, n):

words = [w.strip(".,;:!?") for w in text.lower().split()]

return Counter(w for w in words if w).most_common(n)

On "The cat saw the dog. The dog saw the cat run." with n=3n = 3: [('the', 4), ('cat', 2), ('saw', 2)]; cat comes before saw and dog, met first.

Exercise 20.12 ★★★

Design, in prose, the interface of a module of queues, the waiting line where the first in is the first out: the names of the functions and the specification of each, including what happens on an empty queue.

Solution

Solution of Exercise 20.12.

One possible interface:

  • new_queue(): returns a new empty queue;
  • push(q, x): adds x at the end of q;
  • pop(q): removes and returns the element at the front, the earliest pushed of those still there; on an empty queue it raises IndexError and leaves the queue unchanged;
  • is_empty(q): returns True when q holds no element;
  • size(q): returns the number of elements of q.

Nothing says how the elements are kept: a list, or two lists, could implement it, and a later chapter does.

Exercise 20.13 ★★★

Write a module dates_chosen that offers the five names of the interface, taken from dateset_list when the environment variable DATESET is list, and from dateset_set otherwise. How can a single test file check both?

Solution

Solution of Exercise 20.13.

import os

if os.environ.get("DATESET", "set") == "list":

from dateset_list import add, contains, empty, from_dates, size

else:

from dateset_set import add, contains, empty, from_dates, size

The choice is made once, at the first import. A test file can run the same tests twice, in two separate runs, DATESET=list python tests.py and DATESET=set python tests.py; or, within one run, set the variable, remove dates_chosen from sys.modules so that it is imported again, and import it again. (The chapter’s dateset_tests.py makes the choice differently, from the command line.)

Exercise 20.14 ★★★

Twenty programs call contains in about ten places each. Compare how many lines of user code change when the implementation changes from list to set, and when the interface renames contains to has.

Solution

Solution of Exercise 20.14.

Implementation changed, interface kept: no line of the twenty programs changes, or at most the import line of each, 2020 lines, if the module’s name changes. Interface changed: each of the 20×10=20020 \times 10 = 200 calls is rewritten, in programs written by others, and any missed one fails only when it runs. A change behind the interface costs the module’s author alone; a change of the interface costs every user.

Exercise 20.15 ★★★

The module primes computes, at its top level, all the primes below a million, and prints computing the primes below 1000000.... Every program that imports it, even to read a constant, prints the message and waits. Correct the module so that the work is done only when a prime is first asked for.

Solution

Solution of Exercise 20.15.

LIMIT = 1_000_000

_sieve = None

def is_prime(n):

if _sieve is None:

_build()

return _sieve[n]

_build holds the sieve of the old top level, assigning the global _sieve; the message is gone. Importing now only defines names; the first call to is_prime pays for the sieve, once. The tests check that importing prints nothing and that both versions agree below 20002000.

20.7 Problem: The Calendar Module

Problem 20.1

Weekend problem — a module three times rewritten

The town’s date module now has three implementations behind one interface. The third keeps the dates in a sorted list and searches it by halving. The program below measures contains in all three, for n=103n = 10^3, 10410^4 and 10510^5 dates.

import bisect


def empty():
    """Return a new set of dates, with no date in it."""
    return []


def from_dates(dates):
    """Return a new set holding the dates of the iterable dates."""
    return sorted(set(dates))


def add(s, d):
    """Add the date d to s; nothing changes if d is already in s."""
    if not contains(s, d):
        bisect.insort(s, d)


def contains(s, d):
    """Return True when the date d is in s."""
    i = bisect.bisect_left(s, d)
    return i < len(s) and s[i] == d


def size(s):
    """Return the number of dates in s."""
    return len(s)
Listing 20.10. The third implementation: a sorted list. code/grade-11/09-modules-and-interfaces/listings/dateset_sorted.py
"""Time contains(s, d) in the three implementations, for n dates."""
import statistics
import time
from datetime import date, timedelta

import dateset_list
import dateset_set
import dateset_sorted

START = date(1800, 1, 1)


def per_lookup(ds, s, targets, runs=5, repeat=10):
    times = []
    for _ in range(runs):
        begin = time.perf_counter()
        for _ in range(repeat):
            for d in targets:
                ds.contains(s, d)
        times.append((time.perf_counter() - begin) / (repeat * len(targets)))
    return statistics.median(times)


if __name__ == "__main__":
    print(f"{'n':>7} {'list':>10} {'sorted':>10} {'set':>10}   (per lookup)")
    for n in [1000, 10_000, 100_000]:
        days = [START + timedelta(days=2 * i) for i in range(n)]   # one day in two
        targets = [days[-1], days[-1] - timedelta(days=1)]   # present, absent
        row = []
        for ds in [dateset_list, dateset_sorted, dateset_set]:
            s = ds.from_dates(days)
            row.append(per_lookup(ds, s, targets))
        print(f"{n:>7}", " ".join(f"{t * 1e6:8.2f} us" for t in row))
    print(f"at n = 100000, the set is {row[0] / row[2]:,.0f} times faster",
          "than the list")
Listing 20.11. One lookup, three implementations. code/grade-11/09-modules-and-interfaces/listings/measure_dateset.py
$ python measure_dateset.py
      n       list     sorted        set   (per lookup)
   1000     5.72 us     0.24 us     0.06 us
  10000    48.28 us     0.19 us     0.06 us
 100000   501.27 us     0.23 us     0.06 us
at n = 100000, the set is 7,900 times faster than the list
Output 20.8. Measured on the author’s laptop, in microseconds per lookup.
contains measured on the author’s laptop (figures/measured_contains.py, a separate run). On both axes each step multiplies by 10. The list climbs in step with n; the two others stay flat.
contains measured on the author’s laptop (figures/measured_contains.py, a separate run). On both axes each step multiplies by 1010. The list climbs in step with nn; the two others stay flat.

Part I — A module of dates.

  1. With the leap-year rule of chapter 1, how many days have the years 20282028, 21002100 and 20002000?
  2. What does size return for a set of dates holding every day of 20282028?
  3. date(2027, 2, 29) raises ValueError: day is out of range for month. Why is this a good behaviour for a module of dates?
  4. From the output of stdlib_tour.py, on which day of the week is 20 November 2026, and which date comes 100100 days later?

Part II — The interface and its tests.

  1. List the five names of the interface, with the specification of each in one sentence.
  2. Which test checks that adding the same date twice keeps one copy?
  3. Why do the tests call only the five names of the interface?
  4. What should python dateset_tests.py sorted print?
  5. Write one more test: from_dates([]) gives a set of size 00.

Part III — Three implementations.

  1. In dateset_sorted, which function relies on the list being sorted, and which keeps it sorted?
  2. For n=105n = 10^5, how many dates does contains look at, at most, in the list, and in the sorted list?
  3. Why does from_dates in dateset_list use dict.fromkeys rather than list(dates)?
  4. Why is add slower than contains in the sorted implementation?

Part IV — Measured cost.

  1. By how much is the list’s time multiplied from n=103n = 10^3 to n=105n = 10^5? Is it what the count predicts?
  2. How do the sorted list and the set behave as nn grows?
  3. Predict the list’s time per lookup for n=106n = 10^6.
  4. A program makes a thousand lookups in 10510^5 dates. How long does it take with each implementation?
  5. The measurement uses from_dates to build the sets. Why not nn calls to add?
  6. Which lines of use_dateset.py would change to use dateset_sorted?
  7. State the result: the speed-up of the set over the list at n=105n = 10^5, and what happened to the tests.
Solution

Solution of Problem 20.1.

1. 20282028: divisible by 44, not a century year: 366366 days. 21002100: a century year not divisible by 400400: 365365. 20002000: divisible by 400400: 366366.

2. 366366.

3. An impossible date is refused where it is made, with a message that names the problem, instead of entering a set silently and causing a wrong answer far away.

4. weekday() is 44: a Friday. 100100 days later is 28 February 2027.

5. empty() returns a new set with no date; from_dates(dates) returns a new set holding the dates given, each once; add(s, d) adds d to s, and does nothing if it is there; contains(s, d) tells whether d is in s; size(s) returns the number of dates in s.

6. test_add_twice.

7. So that they check only the promises, which every implementation must keep; a test using append would fail on a correct implementation with a set.

8. implementation: dateset_sorted, then the three lines ending in ok, the line of dashes and OK.

9.

def test_from_nothing(self):

self.assertEqual(ds.size(ds.from_dates([])), 0)

10. contains relies on it: bisect_left halves the list as binary search does, which is right only on a sorted list. from_dates sorts, and add inserts with insort at the right place.

11. The list: up to 100 000100\,000 dates. The sorted list: h(105)+1=17h(10^5) + 1 = 17.

12. list(dates) would keep repeated dates, and size would count them twice; dict.fromkeys keeps each date once, in the order of first appearance.

13. After the search, insort must make room: every later date moves one place, up to nn moves.

14. From 5.725.72 to 501.27501.27 μ\mus: about 8888 times, for 100100 times more dates. The count predicts 100100; at small nn, the fixed cost of each call weighs more.

15. They hardly change: the sorted list stays near 0.20.2 μ\mus (1717 dates looked at instead of 1010), the set near 0.060.06 μ\mus.

16. About ten times more: 55 ms per lookup.

17. The list, 1000×5011000 \times 501 μ\mus, about half a second; the sorted list, about 0.230.23 ms; the set, about 0.060.06 ms.

18. Each add on the list scans it: nn calls look at about n2/2n^2/2 dates, 5×1095 \times 10^9 for n=105n = 10^5, far too long for a measurement; from_dates is linear.

19. The import lines and the list [dateset_list, dateset_set]; none of the lines using the dates.

20. At n=105n = 10^5 dates, the set answers contains about 79007900 times faster than the list (0.060.06 against 501501 μ\mus per lookup, on the author’s laptop), and the same tests pass, unchanged, on every implementation.

本章定义的术语

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