A riff on Cook-Levin Chapters

Chapter 4

Deciding in plain Python

A problem is four answers, one per input, so deciding one takes a line of ordinary code. The code here is python/decides.py, which build.shale runs on every build: it holds its two versions to each other on all 16 problems and all four inputs, and each one-line test below to its problem.

Two versions of decides §

A problem's want code has bit n set when input n is in it, as in the table of “Programs as formal languages”: {0, 2, 3} is 1 + 4 + 8 = 13. The plain version lists the members and looks n up among them:

python/decides.py, an excerpt
def decides(want, n):
    # The members of the problem: each input whose bit is set in `want`.
    members = []
    for i in range(4):
        if want & (1 << i):
            members.append(i)
    # The problem holds n when n is one of its members.
    return n in members

The golfed version reads bit n of want directly:

python/decides.py, an excerpt
decides_golfed = lambda want, n: want >> n & 1

Some problems as one test §

Many of the 16 problems have a natural test of n, or of its two bits, hb and lb (n is 2·hb + lb):

python/decides.py, an excerpt
ONE_LINERS = {
    14: lambda n: n != 0,  # {1, 2, 3}
    5: lambda n: n % 2 == 0,  # {0, 2}
    8: lambda n: n == 3,  # {3}
    6: lambda n: n in (1, 2),  # {1, 2}: hb XOR lb

“The problems, seen from outside” lists all 16 this way, as Boolean expressions of the two bits.

What the machine adds §

The want code already says everything about a problem. The Nibble machine takes up to six lines to say the same thing, and for {0, 2, 3} it takes all six, in its one program. The composed polynomial of “Six steps composed”, which runs every program on every input at once, takes 10,324 terms. The machine is there to be the thing analysed, a small checker that Cook and Levin's construction can turn into a formula; the question it answers is a lookup.