---
title: "Propositional Logic"
book: "University Computer Science — Year 1"
subject: computer-science
language: en
chapter: 10
exercises: 12
source: https://one-course.com/books/computer-science/3/en/chapter/10-propositional-logic
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 10 — Propositional Logic

Four friends are invited to dinner, and each has a condition. Ana comes only if Ben comes. Ben and Cyd will not both come. Cyd or Dee must come, but Dee will not come without Ana. Who can come? Four people make sixteen possible guest lists, few enough to try by hand; seven people with a dozen conditions make thousands, and the schedules, circuits and configurations that programs check daily make more lists than any computer could ever try. This chapter writes such conditions as formulas, represents the formulas as trees in Python, evaluates them, rewrites them into standard forms, and decides with a short recursive algorithm whether any list satisfies them all.

**You already know.**

A statement is true or false; *not*, *and*, *or*, *if … then* and *if and only if* combine statements, and a truth table gives the value of a combination for every value of its parts. Logic gates compute the same operations on bits.

## 10.1 Formulas as trees

**Definition 10.1 (Propositional variable, connective, formula).**

A *propositional variable* is a name, $p$, $q$, $\mathit{ana}$, that stands for a statement which is either true or false. The *connectives* are $\neg$ (not), of arity one, and $\wedge$ (and), $\vee$ (or), $\rightarrow$ (implies) and $\leftrightarrow$ (if and only if), of arity two. The *propositional formulas* are defined inductively: every variable is a formula; if $\varphi$ is a formula, so is $\neg\varphi$; if $\varphi$ and $\psi$ are formulas, so are $(\varphi \wedge \psi)$, $(\varphi \vee \psi)$, $(\varphi \rightarrow \psi)$ and $(\varphi \leftrightarrow \psi)$; and nothing else is.

A formula is a tree: a variable is a leaf, and a [connective](#def-b1-propositional-logic-formula) is a node whose children are the formulas it combines. Parentheses exist only to write the tree on one line; the usual conventions drop some of them: $\neg$ binds tighter than $\wedge$, which binds tighter than $\vee$, then $\rightarrow$ and $\leftrightarrow$; $\wedge$ and $\vee$ group to the left, $\rightarrow$ to the right, so that $p \rightarrow q \rightarrow r$ means $p \rightarrow (q \rightarrow r)$.

```python
class Formula:
    """Python's operators build formulas: ~p, p & q, p | q, p >> q (implies)."""

    def __invert__(self):
        return Not(self)

    def __and__(self, other):
        return Bin("&", self, other)

    def __or__(self, other):
        return Bin("|", self, other)

    def __rshift__(self, other):
        return Bin("->", self, other)

    def __str__(self):
        return show(self)


@dataclass(frozen=True)
class Var(Formula):
    name: str


@dataclass(frozen=True)
class Not(Formula):
    sub: Formula


@dataclass(frozen=True)
class Bin(Formula):
    op: str  # "&", "|", "->" or "<->"
    left: Formula
    right: Formula

```

***Listing 10.1.** Formulas as Python data code/bachelor-1/10-propositional-logic/listings/formula.py*

Each kind of node is a class, and Python’s operators build trees: `~p` is `Not(p)`, `p & q` is `Bin("&", p, q)`, and `p >> q`, borrowed for implication, is `Bin("->", p, q)`. Python’s own precedence puts `>>` above `&`, so the listings always put an implication between parentheses. The classes are *frozen*, so that a formula cannot change once built and can be put in a set.

**Definition 10.2 (Subformula, size, height).**

The *subformulas* of a formula are the formulas of the subtrees of its tree, itself included. The *size* of a formula is the number of nodes of its tree: 1 for a variable, $1 +
\text{size}(\varphi)$ for $\neg\varphi$, $1 + \text{size}(\varphi) + \text{size}(\psi)$ for a binary [connective](#def-b1-propositional-logic-formula). Its *height* is the length of the longest path from the root to a leaf: 0 for a variable, $1 + \text{height}(\varphi)$, and $1 + \max(\text{height}(\varphi), \text{height}(\psi))$.

```python
def size(f):
    match f:
        case Var():
            return 1
        case Not(sub):
            return 1 + size(sub)
        case Bin(_, left, right):
            return 1 + size(left) + size(right)


def height(f):
    match f:
        case Var():
            return 0
        case Not(sub):
            return 1 + height(sub)
        case Bin(_, left, right):
            return 1 + max(height(left), height(right))

```

***Listing 10.2.** [Size](#def-b1-propositional-logic-size) and [height](#def-b1-propositional-logic-size), by induction on the formula code/bachelor-1/10-propositional-logic/listings/formula.py*

The definitions follow the inductive definition of formulas, one case per rule, and so do the functions, with Python’s `match`: a function defined this way is defined on every formula, since every formula is built by the rules. The next chapter proves properties of such functions by the same induction ([Chapter 11](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#ch-b1-induction-and-termination)); for instance that the [height](#def-b1-propositional-logic-size) is always smaller than the [size](#def-b1-propositional-logic-size).

```
$ python formula.py
formula: (p -> q) & ~(q | r)
&
    ->
        p
        q
    ~
        |
            q
            r
size 8 height 3 variables ['p', 'q', 'r']
7 subformulas: ['p', 'q', 'r', 'q | r', 'p -> q', '~(q | r)', '(p -> q) & ~(q | r)']
p & (q & r)
p & q & r
p -> q -> r
(p -> q) -> r
~(p | q) | ~p
p <-> (q <-> r)
```

***Output 10.1.** A formula, its tree printed with indentation, its [size](#def-b1-propositional-logic-size), [height](#def-b1-propositional-logic-size) and [subformulas](#def-b1-propositional-logic-size), and six formulas written with only the necessary parentheses.*

![The tree of (p q) (q r). Its size counts nodes, its height the links on the longest path from the root. The root’s connective, , says what kind of formula it is: a conjunction.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-propositional-logic/fig-42a2c8c29014.svg)

*The tree of $(p \rightarrow q) \wedge \neg(q \vee r)$. Its [size](#def-b1-propositional-logic-size) counts nodes, its [height](#def-b1-propositional-logic-size) the links on the longest path from the root. The root’s [connective](#def-b1-propositional-logic-formula), $\wedge$, says what kind of formula it is: a conjunction.*

## 10.2 Valuations and truth

**Definition 10.3 (Valuation, truth value).**

A *valuation* assigns to each variable a value, true ($\mathrm{T}$) or false ($\mathrm{F}$). The *truth value* of a formula under a valuation $v$ is defined by induction: a variable has the value $v$ gives it; $\neg\varphi$ is true when $\varphi$ is false; $\varphi \wedge \psi$ when both are true; $\varphi
\vee \psi$ when at least one is; $\varphi \rightarrow \psi$ unless $\varphi$ is true and $\psi$ false; $\varphi
\leftrightarrow \psi$ when both have the same value.

```python
TABLES = {"&": lambda a, b: a and b, "|": lambda a, b: a or b,
          "->": lambda a, b: (not a) or b, "<->": lambda a, b: a == b}


def value(f, v):
    """v maps each variable name of f to True or False."""
    match f:
        case Var(name):
            return v[name]
        case Not(sub):
            return not value(sub, v)
        case Bin(op, left, right):
            return TABLES[op](value(left, v), value(right, v))


def valuations(names):
    """All 2**len(names) valuations of the names, in the order of a truth table."""
    for bits in product([False, True], repeat=len(names)):
        yield dict(zip(names, bits))


def models(f):
    return [v for v in valuations(variables(f)) if value(f, v)]


def is_tautology(f):
    return len(models(f)) == 2 ** len(variables(f))


def is_satisfiable(f):
    return any(value(f, v) for v in valuations(variables(f)))
```

***Listing 10.3.** [Truth values](#def-b1-propositional-logic-valuation), [valuations](#def-b1-propositional-logic-valuation) and [models](#def-b1-propositional-logic-model) code/bachelor-1/10-propositional-logic/listings/evaluate.py*

The [truth value](#def-b1-propositional-logic-valuation) of a formula depends only on the values of its own variables, so with $n$ variables a formula has $2^n$ [valuations](#def-b1-propositional-logic-valuation) to consider: the rows of its truth table, which `valuations` lists in the usual order, false before true, with the last variable changing fastest.

**Definition 10.4 (Model, satisfiable, tautology, antilogy).**

A [valuation](#def-b1-propositional-logic-valuation) under which a formula is true is a *model* of it. A formula is *satisfiable* if it has a model, a *tautology* if every [valuation](#def-b1-propositional-logic-valuation) is a model, and an *antilogy* (or contradiction) if none is. A [valuation](#def-b1-propositional-logic-valuation) is a model of a set of formulas if it is a model of each.

```
$ python evaluate.py
(p -> q) & ~(q | r) under p=F q=F r=F: True
(p -> q) & ~(q | r) under p=T q=F r=F: False
models of (p -> q) & ~(q | r) : [{'p': False, 'q': False, 'r': False}]
p | ~p                   tautology True   satisfiable True
p & ~p                   tautology False  satisfiable False
(p -> q) | (q -> p)      tautology True   satisfiable True
((p -> q) -> p) -> p     tautology True   satisfiable True
p -> p & q               tautology False  satisfiable True
```

***Output 10.2.** Two [truth values](#def-b1-propositional-logic-valuation), the only [model](#def-b1-propositional-logic-model) of the formula, and five formulas classified.*

**Definition 10.5 (Logical equivalence, logical consequence).**

Two formulas are *logically equivalent*, written $\varphi \equiv \psi$, if they have the same [truth value](#def-b1-propositional-logic-valuation) under every [valuation](#def-b1-propositional-logic-valuation). A formula $\varphi$ is a *logical consequence* of a set of formulas $\Gamma$, written $\Gamma \models \varphi$, if every [model](#def-b1-propositional-logic-model) of $\Gamma$ is a [model](#def-b1-propositional-logic-model) of $\varphi$.

Thus $\varphi$ is a [tautology](#def-b1-propositional-logic-model) exactly when $\varphi \equiv p \vee \neg p$, and $\varphi \equiv \psi$ exactly when $\varphi \leftrightarrow \psi$ is a [tautology](#def-b1-propositional-logic-model). $\{p, p \rightarrow q\} \models q$: in every [model](#def-b1-propositional-logic-model) of the two formulas, $q$ is true. The formula $((p \rightarrow q) \rightarrow p) \rightarrow p$ of [Output 10.2](#out-b1-propositional-logic-evaluate) is a [tautology](#def-b1-propositional-logic-model) although nothing in its shape suggests it; only the [valuations](#def-b1-propositional-logic-valuation) tell.

```python
def truth_table(f):
    names = variables(f)
    rows = [" ".join(names) + " | " + str(f)]
    for v in valuations(names):
        bits = " ".join("TF"[not v[n]] for n in names)
        rows.append(f"{bits} | {'TF'[not value(f, v)]}")
    return rows


def complete_dnf(f):
    """One conjunction of literals per true row: the formula's complete DNF."""
    terms = []
    for v in valuations(variables(f)):
        if value(f, v):
            terms.append(" & ".join(n if v[n] else "~" + n for n in sorted(v)))
    return " | ".join(f"({t})" for t in terms) if terms else "false: no row is true"


if __name__ == "__main__":
    p, q, r = Var("p"), Var("q"), Var("r")
    f = (p >> q) & (q | r)
    print("\n".join(truth_table(f)))
    print("complete DNF:", complete_dnf(f))
```

***Listing 10.4.** A truth table, and one conjunction per true row code/bachelor-1/10-propositional-logic/listings/truth_table.py*

```
$ python truth_table.py
p q r | (p -> q) & (q | r)
F F F | F
F F T | T
F T F | T
F T T | T
T F F | F
T F T | F
T T F | T
T T T | T
complete DNF: (~p & ~q & r) | (~p & q & ~r) | (~p & q & r) | (p & q & ~r) | (p & q & r)
```

***Output 10.3.** The truth table of $(p \rightarrow q) \wedge
(q \vee r)$ and the disjunction read from its true rows.*

![The complete DNF of = (p q) (q r). Each true row becomes the conjunction of literals true exactly on that row; their disjunction is true exactly on the true rows, so it is equivalent to .](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-propositional-logic/fig-4f995e78c618.svg)

*The complete DNF of $\varphi = (p \rightarrow q) \wedge (q \vee r)$. Each true row becomes the conjunction of [literals](#def-b1-propositional-logic-literal) true exactly on that row; their disjunction is true exactly on the true rows, so it is equivalent to $\varphi$.*

## 10.3 Equivalence and normal forms

The following equivalences hold for all formulas $\varphi$, $\psi$, $\chi$; each is checked by a truth table of four or eight rows.

- Double negation: $\neg\neg\varphi \equiv \varphi$ . Excluded middle: $\varphi \vee \neg\varphi$ is a [tautology](#def-b1-propositional-logic-model) .
- De Morgan’s laws: $\neg(\varphi \wedge \psi) \equiv \neg\varphi \vee \neg\psi$ and $\neg(\varphi \vee \psi) \equiv \neg\varphi \wedge \neg\psi$ .
- Distributivity: $\varphi \vee (\psi \wedge \chi) \equiv (\varphi \vee \psi) \wedge (\varphi \vee \chi)$ , and the same with $\wedge$ and $\vee$ exchanged.
- Implication and equivalence rewritten: $\varphi \rightarrow \psi \equiv \neg\varphi \vee \psi$ and $\varphi \leftrightarrow \psi \equiv (\varphi \rightarrow \psi) \wedge (\psi \rightarrow \varphi)$ .

Replacing a [subformula](#def-b1-propositional-logic-size) by an equivalent one gives an equivalent formula, since the [truth value](#def-b1-propositional-logic-valuation) of a formula depends only on the [truth values](#def-b1-propositional-logic-valuation) of its [subformulas](#def-b1-propositional-logic-size). Applied in a fixed order, these laws bring every formula into a standard shape.

**Definition 10.6 (Literal, clause).**

A *literal* is a variable or the negation of a variable: $p$, $\neg p$. A *clause* is a disjunction of literals, $p \vee \neg q \vee r$, and is true when at least one of its literals is; the empty clause, with no literal, is false.

**Definition 10.7 (Negation normal form, CNF, DNF).**

A formula is in *negation normal form* if it uses only $\wedge$, $\vee$ and $\neg$, and $\neg$ only in front of variables. It is in *conjunctive normal form* (CNF) if it is a conjunction of [clauses](#def-b1-propositional-logic-literal), and in *disjunctive normal form* (DNF) if it is a disjunction of conjunctions of [literals](#def-b1-propositional-logic-literal).

```python
def nnf(f, positive=True):
    """An equivalent formula of & and | over literals (of ~f if not positive)."""
    match f:
        case Var():
            return f if positive else Not(f)
        case Not(sub):
            return nnf(sub, not positive)
        case Bin("->", a, b):
            return nnf(~a | b, positive)
        case Bin("<->", a, b):
            return nnf((a >> b) & (b >> a), positive)
        case Bin(op, a, b):  # & or |; De Morgan swaps them under a negation
            if not positive:
                op = "|" if op == "&" else "&"
            return Bin(op, nnf(a, positive), nnf(b, positive))


def literal(g):
    return g.name if isinstance(g, Var) else "~" + g.sub.name


def distribute(g, outer, inner):
    """g in NNF, as a list of sets of literals: an `outer` of `inner`s."""
    match g:
        case Bin(op, a, b) if op == outer:
            return distribute(a, outer, inner) + distribute(b, outer, inner)
        case Bin(op, a, b) if op == inner:
            return [x | y for x in distribute(a, outer, inner)
                    for y in distribute(b, outer, inner)]
        case _:
            return [frozenset([literal(g)])]


def cnf(f):
    return distribute(nnf(f), "&", "|")


def dnf(f):
    return distribute(nnf(f), "|", "&")
```

***Listing 10.5.** [Negation normal form](#def-b1-propositional-logic-normal-forms), then CNF and DNF by distribution code/bachelor-1/10-propositional-logic/listings/normal_forms.py*

`nnf` rewrites $\rightarrow$ and $\leftrightarrow$, then pushes each negation down to the variables with De Morgan’s laws, carrying a flag that says whether the current subtree is negated. `distribute` then turns a formula in [negation normal form](#def-b1-propositional-logic-normal-forms) into a list of sets of [literals](#def-b1-propositional-logic-literal): for a CNF, a conjunction concatenates the [clauses](#def-b1-propositional-logic-literal) of its two sides, and a disjunction takes every union of a [clause](#def-b1-propositional-logic-literal) from the left with a [clause](#def-b1-propositional-logic-literal) from the right, which is distributivity applied as often as needed.

```
$ python normal_forms.py
formula: ~((p -> q) | r)
  NNF: p & ~q & ~r
  CNF: (p) & (~q) & (~r)
  CNF simplified: (p) & (~q) & (~r)
  DNF: (p & ~q & ~r)
  DNF simplified: (p & ~q & ~r)
formula: (p <-> q) | r
  NNF: (~p | q) & (~q | p) | r
  CNF: (~p | q | r) & (p | ~q | r)
  CNF simplified: (~p | q | r) & (p | ~q | r)
  DNF: (~p & ~q) | (p & ~p) | (q & ~q) | (p & q) | (r)
  DNF simplified: (~p & ~q) | (p & q) | (r)
```

***Output 10.4.** Two formulas in their normal forms; the simplified forms drop the sets that hold a [literal](#def-b1-propositional-logic-literal) and its negation.*

Every formula has an equivalent CNF and an equivalent DNF, as these functions show, and as the truth table already showed for the DNF (the [antilogy](#def-b1-propositional-logic-model) has the empty disjunction, and the [tautology](#def-b1-propositional-logic-model) the empty conjunction). But the price can be high.

```python
def pairs(n):
    terms = [Var(f"x{i}") & Var(f"y{i}") for i in range(1, n + 1)]
    return reduce(lambda a, b: a | b, terms)


if __name__ == "__main__":
    print("formula for n = 3:", pairs(3))
    print(" n  size  clauses  simplified")
    for n in range(1, 11):
        f = pairs(n)
        print(f"{n:2d} {size(f):5d} {len(cnf(f)):8d} {len(simplify(cnf(f))):11d}")
```

***Listing 10.6.** A formula of [size](#def-b1-propositional-logic-size) $4n - 1$ and its CNF code/bachelor-1/10-propositional-logic/listings/blowup.py*

```
$ python blowup.py
formula for n = 3: x1 & y1 | x2 & y2 | x3 & y3
 n  size  clauses  simplified
 1     3        2           2
 2     7        4           4
 3    11        8           8
 4    15       16          16
 5    19       32          32
 6    23       64          64
 7    27      128         128
 8    31      256         256
 9    35      512         512
10    39     1024        1024
```

***Output 10.5.** The CNF doubles with each pair: no [clause](#def-b1-propositional-logic-literal) is redundant.*

**Proposition 10.8 (An exponential CNF).**

Every CNF equivalent to $\varphi_n = (x_1 \wedge y_1) \vee \dots \vee (x_n \wedge y_n)$ has at least $2^n$ [clauses](#def-b1-propositional-logic-literal).

**Proof.** Let $C$ be an equivalent CNF. For each choice $s = (s_1, \dots, s_n)$ of one variable $s_i \in \{x_i, y_i\}$ per pair, let $v_s$ make the chosen variables false and the others true. Each pair has a false variable, so $\varphi_n$ is false under $v_s$, and so is $C$: some [clause](#def-b1-propositional-logic-literal) $c$ of $C$ is false under $v_s$, which means its positive [literals](#def-b1-propositional-logic-literal) are among $s_1, \dots, s_n$. Now fix $i$ and let $u$ be $v_s$ with $s_i$ made true. Pair $i$ is now true, so $\varphi_n$ and every [clause](#def-b1-propositional-logic-literal) of $C$ are true under $u$. The [clause](#def-b1-propositional-logic-literal) $c$ changed from false to true, so it contains a [literal](#def-b1-propositional-logic-literal) whose value changed: only $s_i$ changed, and from false to true, so $c$ contains the [literal](#def-b1-propositional-logic-literal) $s_i$. This holds for every $i$, so the positive [literals](#def-b1-propositional-logic-literal) of $c$ are exactly $s_1, \dots, s_n$. Two different choices give [clauses](#def-b1-propositional-logic-literal) with different positive [literals](#def-b1-propositional-logic-literal), hence different [clauses](#def-b1-propositional-logic-literal): there are at least $2^n$ of them. ∎

A formula of [size](#def-b1-propositional-logic-size) 39 needs a CNF of 1024 [clauses](#def-b1-propositional-logic-literal); one of [size](#def-b1-propositional-logic-size) 399 needs more [clauses](#def-b1-propositional-logic-literal) than any computer can hold. Yet the next section’s algorithm wants a CNF. The way out is to stop asking for an equivalent formula.

**Definition 10.9 (Equisatisfiable formulas).**

Two formulas, or sets of [clauses](#def-b1-propositional-logic-literal), are *equisatisfiable* if both are [satisfiable](#def-b1-propositional-logic-model) or neither is. Equivalent formulas are equisatisfiable; equisatisfiable formulas need not even have the same variables.

The problem of this chapter builds, for every formula, an [equisatisfiable](#def-b1-propositional-logic-equisat) CNF of [size](#def-b1-propositional-logic-size) proportional to the formula’s, by adding one new variable per [connective](#def-b1-propositional-logic-formula): Tseitin’s encoding, named after the logician Grigori Tseitin.

## 10.4 Satisfiability

**Definition 10.10 (Satisfiability problem, kkk-SAT).**

The *satisfiability problem* (SAT) asks, given a formula, usually as a set of [clauses](#def-b1-propositional-logic-literal), whether it has a [model](#def-b1-propositional-logic-model), and if so for one. *$k$-SAT* is the same problem for sets of [clauses](#def-b1-propositional-logic-literal) with at most $k$ [literals](#def-b1-propositional-logic-literal) each.

Trying the $2^n$ [valuations](#def-b1-propositional-logic-valuation) answers it, and `models` in [Listing 10.3](#lst-b1-propositional-logic-evaluate) does exactly that; with 49 variables it would try more than $5 \times 10^{14}$ [valuations](#def-b1-propositional-logic-valuation). A better method stops as soon as part of a [valuation](#def-b1-propositional-logic-valuation) decides the answer.

**Method 10.11 (Quine’s algorithm).**

To decide a set of [clauses](#def-b1-propositional-logic-literal) $S$:

1. If $S$ is empty, it is satisfied: return the empty [valuation](#def-b1-propositional-logic-valuation) . If $S$ contains the empty [clause](#def-b1-propositional-logic-literal) , it is unsatisfiable: return “none”.
2. Otherwise choose a variable $x$ of $S$ . Make $x$ true: remove the [clauses](#def-b1-propositional-logic-literal) that contain $x$ , and remove the [literal](#def-b1-propositional-logic-literal) $\neg x$ from the others. Decide the result recursively; if it has a [model](#def-b1-propositional-logic-model) , add $x$ true to it and return it.
3. Otherwise make $x$ false in the same way, and decide again.

The algorithm is named after the logician Willard Van Orman Quine; it is also called splitting.

```python
def neg(lit):
    return lit[1:] if lit.startswith("~") else "~" + lit


def assign(clauses, lit):
    """Make lit true: the clauses holding lit are satisfied and vanish,
    and ~lit, now false, leaves the others."""
    return [c - {neg(lit)} for c in clauses if lit not in c]


def quine(clauses, stats):
    """A set of literals whose truth satisfies every clause, or None if no
    valuation does. stats["nodes"] counts the calls (the search-tree nodes)."""
    stats["nodes"] += 1
    if not clauses:
        return set()  # nothing left to satisfy
    if frozenset() in clauses:
        return None  # an empty clause: every literal of it was made false
    x = min(clauses[0], key=lambda lit: lit.lstrip("~")).lstrip("~")
    for lit in (x, neg(x)):
        model = quine(assign(clauses, lit), stats)
        if model is not None:
            return model | {lit}
    return None

```

***Listing 10.7.** Quine’s algorithm, counting its nodes code/bachelor-1/10-propositional-logic/listings/quine.py*

```
$ python quine.py
p q, ~p q, p ~q, ~p ~q         model None  nodes 7
p q r, ~p, ~q, r ~s, s ~r      model ['r', 's', '~p', '~q']  nodes 7
```

***Output 10.6.** An unsatisfiable set of four [clauses](#def-b1-propositional-logic-literal) and a [satisfiable](#def-b1-propositional-logic-model) one; seven calls each.*

**Proposition 10.12 (Correctness of Quine’s algorithm).**

On every finite set of [clauses](#def-b1-propositional-logic-literal) $S$, Quine’s algorithm terminates, returns a [valuation](#def-b1-propositional-logic-valuation) of some variables that satisfies every [clause](#def-b1-propositional-logic-literal) of $S$ if $S$ is [satisfiable](#def-b1-propositional-logic-model) (the other variables may take any value), and returns “none” otherwise.

**Proof.** By induction on the number $n$ of variables of $S$. If $n = 0$, $S$ is empty or holds only empty [clauses](#def-b1-propositional-logic-literal), and step 1 answers correctly. Let $n \geq 1$, and suppose step 1 does not apply. Let $S_x$ and $S_{\neg x}$ be the sets obtained by making $x$ true and false; each has at most $n - 1$ variables, so by induction the recursive calls terminate and answer correctly. A [valuation](#def-b1-propositional-logic-valuation) $v$ with $v(x) = \mathrm{T}$ satisfies $S$ exactly when it satisfies $S_x$: the removed [clauses](#def-b1-propositional-logic-literal) contain $x$ and are true, and the removed [literals](#def-b1-propositional-logic-literal) $\neg x$ are false and change nothing. The same holds with $\mathrm{F}$ and $S_{\neg x}$. Every [valuation](#def-b1-propositional-logic-valuation) gives $x$ one of the two values, so $S$ is [satisfiable](#def-b1-propositional-logic-model) exactly when $S_x$ or $S_{\neg x}$ is, and the returned [valuation](#def-b1-propositional-logic-valuation), extended with the value of $x$, satisfies $S$. ∎

The search is a binary tree whose nodes are the calls; `stats` counts them. In the worst case the tree is complete and has about $2^{n + 1}$ nodes, no better than the truth table; in practice whole subtrees are never visited, because a [clause](#def-b1-propositional-logic-literal) becomes empty early or the [clauses](#def-b1-propositional-logic-literal) run out.

**Definition 10.13 (Unit propagation).**

A *unit [clause](#def-b1-propositional-logic-literal)* is a [clause](#def-b1-propositional-logic-literal) of one [literal](#def-b1-propositional-logic-literal). *Unit propagation* makes the [literal](#def-b1-propositional-logic-literal) of each unit [clause](#def-b1-propositional-logic-literal) true, without trying the other value, and repeats while unit [clauses](#def-b1-propositional-logic-literal) remain: a [valuation](#def-b1-propositional-logic-valuation) that makes the [literal](#def-b1-propositional-logic-literal) false falsifies the [clause](#def-b1-propositional-logic-literal), so no [model](#def-b1-propositional-logic-model) is lost.

Splitting on $x$ often creates [unit clauses](#def-b1-propositional-logic-unit): $\neg x \vee y$ becomes $y$ as soon as $x$ is true. Propagating them before choosing the next variable cuts the tree a great deal ([Exercise 10.11](#exo-b1-propositional-logic-11)). Solvers used in industry add many refinements to this algorithm, and decide sets of millions of [clauses](#def-b1-propositional-logic-literal) that come from circuits, schedules and programs.

## 10.5 Modelling with formulas

The dinner of the opening question has one variable per friend, $\mathit{ana}$ meaning “Ana comes”, and one formula per condition.

```python
ana, ben, cyd, dee = Var("ana"), Var("ben"), Var("cyd"), Var("dee")
rules = [ana >> ben,                   # Ana comes only if Ben comes
         ~(ben & cyd),                 # Ben and Cyd will not both come
         (cyd | dee) & (dee >> ana)]   # Cyd or Dee comes; Dee only with Ana
dinner = rules[0] & rules[1] & rules[2]
clauses = cnf(dinner)

if __name__ == "__main__":
    print("formula:", dinner)
    for v in models(dinner):
        print("model:", ", ".join(name for name in v if v[name]))
    print("CNF:", show_sets(clauses, "&", "|"))
    stats = {"nodes": 0}
    model = quine(clauses, stats)
    print("Quine's algorithm:", sorted(model), "after", stats["nodes"], "nodes")
    everyone = dinner & ana & ben & cyd & dee
    print("everyone comes:", models(everyone) or "no model")
```

***Listing 10.8.** Who can come to dinner? code/bachelor-1/10-propositional-logic/listings/puzzle.py*

```
$ python puzzle.py
formula: (ana -> ben) & ~(ben & cyd) & ((cyd | dee) & (dee -> ana))
model: cyd
model: ana, ben, dee
CNF: (~ana | ben) & (~ben | ~cyd) & (cyd | dee) & (ana | ~dee)
Quine's algorithm: ['ana', 'ben', 'dee', '~cyd'] after 6 nodes
everyone comes: no model
```

***Output 10.7.** Two guest lists out of sixteen; not everyone can come.*

![Quine’s algorithm on the CNF of the dinner (initials for the names). The six nodes are the six calls counted in ; the dashed branches are never visited, since a model was found first. The model read on the path: a, b, d true, c false.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-propositional-logic/fig-c31491ccf87d.svg)

*Quine’s algorithm on the CNF of the dinner (initials for the names). The six nodes are the six calls counted in [Output 10.7](#out-b1-propositional-logic-puzzle); the dashed branches are never visited, since a [model](#def-b1-propositional-logic-model) was found first. The [model](#def-b1-propositional-logic-model) read on the path: $a$, $b$, $d$ true, $c$ false.*

**Definition 10.14 (Colouring of a graph).**

A *colouring* of a graph with $k$ colours gives each vertex one of $k$ colours so that the two ends of every edge have different colours; a graph that has one is *$k$-colourable*.

The town’s 39 friends are to be seated at three tables so that no two friends share a table, to make them meet new people: a 3-colouring of the friendship graph. The variable $\mathit{red}_5$ says that person 5 is red; each person gets some colour, and each friendship forbids, for each colour, that both friends have it.

```python
def colouring_cnf(people, edges, colours):
    """Variable red5 says: person 5 is red."""
    clauses = [frozenset(f"{c}{p}" for c in colours) for p in people]  # some colour
    for a, b in edges:  # two friends never share a colour
        clauses += [frozenset([f"~{c}{a}", f"~{c}{b}"]) for c in colours]
    return clauses


if __name__ == "__main__":
    edges = friendships()
    people = sorted({p for edge in edges for p in edge})
    for k in (2, 3):
        clauses, stats = colouring_cnf(people, edges, COLOURS[:k]), {"nodes": 0}
        model = quine(clauses, stats)
        print(f"{k} colours: {len(people) * k} variables, {len(clauses)} clauses,",
              "satisfiable" if model is not None else "unsatisfiable",
              f"({stats['nodes']} nodes)")
    print("model checked:", satisfies(model, clauses))
    colour = {p: next(c for c in COLOURS if f"{c}{p}" in model) for p in people}
    for c in COLOURS:
        print(f"{c:5}:", *[p for p in people if colour[p] == c])
    print("friends of equal colour:", sum(colour[a] == colour[b] for a, b in edges))
```

***Listing 10.9.** [Colouring](#def-b1-propositional-logic-colouring) the friendship graph by SAT code/bachelor-1/10-propositional-logic/listings/colouring.py*

```
$ python colouring.py
2 colours: 78 variables, 139 clauses, unsatisfiable (253 nodes)
3 colours: 117 variables, 189 clauses, satisfiable (185 nodes)
model checked: True
red  : 3 4 7 10 12 13 14 15 16 23 34 37 38 39
green: 5 9 11 19 20 21 27 28 31 32 35
blue : 1 2 6 8 17 18 22 24 25 26 29 30 33 36
friends of equal colour: 0
```

***Output 10.8.** Two colours are not enough; three are, and the [model](#def-b1-propositional-logic-model) is read back as three tables.*

![The friendship graph coloured by the model of : red, green and blue. No edge joins two vertices of the same colour. Two colours fail because the graph has a cycle of odd length (the friends 1, 5 and 12 form a triangle), which cannot alternate between two colours.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-propositional-logic/fig-ce71ca08306f.svg)

*The friendship graph coloured by the [model](#def-b1-propositional-logic-model) of [Output 10.8](#out-b1-propositional-logic-colouring): red, green and blue. No edge joins two vertices of the same colour. Two colours fail because the graph has a cycle of odd length (the friends 1, 5 and 12 form a triangle), which cannot alternate between two colours.*

The [clauses](#def-b1-propositional-logic-literal) do not say that a person has at most one colour. They need not: in a [model](#def-b1-propositional-logic-model) where a person has two, either colour can be kept, and the program keeps the first. Leaving out [clauses](#def-b1-propositional-logic-literal) that cannot change the answer keeps the encoding small; adding them makes the [model](#def-b1-propositional-logic-model) easier to read. Either way, the [model](#def-b1-propositional-logic-model) is checked against the [clauses](#def-b1-propositional-logic-literal) before it is used, and the [colouring](#def-b1-propositional-logic-colouring) against the edges.

**Safe use.**

A [model](#def-b1-propositional-logic-model) is only as good as the encoding. A forgotten rule gives [models](#def-b1-propositional-logic-model) that obey the formula and not the world; a wrong rule can make the formula unsatisfiable and the problem seem impossible. Check a [model](#def-b1-propositional-logic-model) against the original constraints with a separate program, and test the encoding on cases small enough to enumerate.

## 10.6 Exercises

**Exercise 10.1 ★.**

Give the [truth value](#def-b1-propositional-logic-valuation) of $\neg(p \wedge q) \rightarrow (r \vee \neg p)$ when $p$ is true and $q$, $r$ are false.

**Solution of Exercise 10.1.**

$p \wedge q$ is false, so $\neg(p \wedge q)$ is true; $\neg p$ is false and $r$ is false, so $r \vee \neg p$ is false. An implication from true to false is false: the formula is false.

```
1. ~(p & q) -> r | ~p under p=T q=F r=F: False
```

***Output 10.12.** The check. Some lines are left out.*

**Exercise 10.2 ★.**

Draw the tree of $((p \vee \neg q) \rightarrow r) \wedge \neg\neg p$. Give its [size](#def-b1-propositional-logic-size), its [height](#def-b1-propositional-logic-size) and the number of its [subformulas](#def-b1-propositional-logic-size).

**Solution of Exercise 10.2.**

The root is $\wedge$; its left child is $\rightarrow$, with children $\vee$ (over $p$ and $\neg$ over $q$) and $r$; its right child is $\neg$ over $\neg$ over $p$. Ten nodes: [size](#def-b1-propositional-logic-size) 10. The longest path, $\wedge$, $\rightarrow$, $\vee$, $\neg$, $q$, has four links: [height](#def-b1-propositional-logic-size) 4. The [subformulas](#def-b1-propositional-logic-size) are $p$, $q$, $\neg q$, $p \vee \neg q$, $r$, $(p \vee \neg q)
\rightarrow r$, $\neg p$, $\neg\neg p$ and the formula: nine, the two leaves $p$ being one formula.

```
2. (p | ~q -> r) & ~~p size 10 height 4 subformulas 9
```

***Output 10.13.** The check. Some lines are left out.*

**Exercise 10.3 ★.**

Which of these formulas are tautologies, which are antilogies, and which are neither? (a) $(p \rightarrow q) \rightarrow (\neg q \rightarrow \neg p)$; (b) $(p \rightarrow q) \rightarrow (q \rightarrow p)$; (c) $p \vee (p \rightarrow q)$; (d) $\neg(p \rightarrow (q \rightarrow p))$.

**Solution of Exercise 10.3.**

(a) A [tautology](#def-b1-propositional-logic-model): its right side is false only when $q$ is false and $p$ true, which makes $p \rightarrow q$ false too (contraposition). (b) Neither: false for $p$ false and $q$ true, true for both true. (c) A [tautology](#def-b1-propositional-logic-model): if $p$ is false, $p \rightarrow q$ is true. (d) An [antilogy](#def-b1-propositional-logic-model): $p \rightarrow (q \rightarrow p)$ is false only if $p$ is true and $q
\rightarrow p$ false, which needs $p$ false.

```
3. (p -> q) -> ~q -> ~p : tautology
3. (p -> q) -> q -> p : satisfiable
3. p | (p -> q) : tautology
3. ~(p -> q -> p) : antilogy
```

***Output 10.14.** The check. Some lines are left out.*

**Exercise 10.4 ★.**

Predict what the program prints, simplified forms included.

```python
p, q, r = Var("p"), Var("q"), Var("r")
f = ~(p & (q | ~r))
print("formula:", f)
print("NNF:", nnf(f))
print("CNF:", show_sets(simplify(cnf(f)), "&", "|"))
print("DNF:", show_sets(simplify(dnf(f)), "|", "&"))
```

***Listing 10.10.** Three normal forms code/bachelor-1/10-propositional-logic/listings/exo_nf.py*

**Solution of Exercise 10.4.**

```
formula: ~(p & (q | ~r))
NNF: ~p | ~q & r
CNF: (~p | ~q) & (~p | r)
DNF: (~p) | (~q & r)
```

***Output 10.15.** The three forms. Some lines are left out.*

De Morgan turns the negated conjunction into $\neg p \vee \neg(q \vee \neg r)$, then $\neg p \vee (\neg q \wedge r)$. The DNF is this formula itself; the CNF distributes $\neg p$ over the conjunction.

**Exercise 10.5 ★★.**

A student’s evaluator reads $p \rightarrow q$ as “if $p$ then $q$”, with the table below. Find the error from the printed rows, explain why `p >> p` is no longer a [tautology](#def-b1-propositional-logic-model), and correct the table.

```python
TABLES = {"&": lambda a, b: a and b, "|": lambda a, b: a or b,
          "->": lambda a, b: b if a else False,  # "if a then b"
          "<->": lambda a, b: a == b}
```

***Listing 10.11.** The implication of the student code/bachelor-1/10-propositional-logic/listings/exo_imp.py*

```
p -> q               F F F T
p -> p               F F T T
(p -> q) | (q -> p)  F F F T
```

***Output 10.9.** Rows for (F,F), (F,T), (T,F), (T,T). Some lines are left out.*

**Solution of Exercise 10.5.**

The rows of $p \rightarrow q$ are F, F, F, T where they should be T, T, F, T: the student makes the implication false whenever $p$ is false, as if it were $p \wedge q$. Then $p \rightarrow p$ is false when $p$ is, and is no [tautology](#def-b1-propositional-logic-model). An implication with a false premise is true: the entry must be `lambda a, b: b if a else True`, that is `(not a) or b`.

**Exercise 10.6 ★★.**

This converter puts all the [literals](#def-b1-propositional-logic-literal) of a disjunction in one [clause](#def-b1-propositional-logic-literal). Find a formula on which it is wrong, explain the mistake with distributivity, and say on which formulas it is right.

```python
def literals(g):
    if isinstance(g, Bin):
        return literals(g.left) | literals(g.right)
    return frozenset([literal(g)])


def cnf_wrong(f):
    g = nnf(f)
    if isinstance(g, Bin) and g.op == "&":
        return cnf_wrong(g.left) + cnf_wrong(g.right)
    return [literals(g)]  # a disjunction: all its literals in one clause

```

***Listing 10.12.** A converter that does not distribute code/bachelor-1/10-propositional-logic/listings/exo_cnf_bug.py*

```
formula: p | q & r  CNF given: (p | q | r)
differ at {'p': False, 'q': False, 'r': True}
differ at {'p': False, 'q': True, 'r': False}
```

***Output 10.10.** Its answer on $p \vee (q \wedge r)$. Some lines are left out.*

**Solution of Exercise 10.6.**

On $p \vee (q \wedge r)$ it gives the single [clause](#def-b1-propositional-logic-literal) $p \vee q \vee r$, true for $p$ and $q$ false and $r$ true, where the formula is false. Distributivity gives $(p \vee q) \wedge (p \vee r)$: a conjunction under a disjunction must be distributed, not flattened. The converter is right on the formulas whose [negation normal form](#def-b1-propositional-logic-normal-forms) has no $\wedge$ below a $\vee$, which are already conjunctions of [clauses](#def-b1-propositional-logic-literal), and wrong on most others (not all: on $p \vee (q \wedge q)$ it happens to be right).

**Exercise 10.7 ★★.**

Write `is_consequence(gamma, phi)`, which decides $\Gamma \models \varphi$ by trying every [valuation](#def-b1-propositional-logic-valuation) of the variables of $\Gamma$ and $\varphi$. Test it on $\{p, p \rightarrow q\} \models q$, on $\{q, p \rightarrow q\}
\not\models p$, and on $\{p, \neg p\} \models q$; explain the last one.

**Solution of Exercise 10.7.**

```python
def is_consequence(gamma, phi):
    """True when every valuation making all of gamma true makes phi true."""
    names = sorted(set(variables(phi)).union(*(variables(g) for g in gamma)))
    for v in valuations(names):
        if all(value(g, v) for g in gamma) and not value(phi, v):
            return False  # a counter-model
    return True
```

*[Logical consequence](#def-b1-propositional-logic-equivalence) by brute force code/bachelor-1/10-propositional-logic/exercises/consequence.py*

$\{p, \neg p\}$ has no [model](#def-b1-propositional-logic-model), so “every [model](#def-b1-propositional-logic-model) of it is a [model](#def-b1-propositional-logic-model) of $q$” holds for want of a counterexample: from a contradiction anything follows. The test `tests/test_formula.py` checks the three cases, and on random formulas that $\Gamma \models \varphi$ exactly when the conjunction of $\Gamma$ implies $\varphi$ is a [tautology](#def-b1-propositional-logic-model).

**Exercise 10.8 ★★.**

Write `exactly_one(lits)`, which returns [clauses](#def-b1-propositional-logic-literal) true exactly when one of the given [literals](#def-b1-propositional-logic-literal) is true, and test it by counting the [models](#def-b1-propositional-logic-model) for up to six [literals](#def-b1-propositional-logic-literal).

**Solution of Exercise 10.8.**

```python


def exactly_one(lits):
    """One clause says "at least one"; one clause per pair says "not both"."""
    at_least = [frozenset(lits)]
    at_most = [frozenset([neg(a), neg(b)]) for a, b in combinations(lits, 2)]
    return at_least + at_most
```

*Exactly one, pairwise code/bachelor-1/10-propositional-logic/listings/exactly.py*

The test `tests/test_formula.py` tries every [valuation](#def-b1-propositional-logic-valuation) for $n \leq 6$: the [models](#def-b1-propositional-logic-model) are exactly the $n$ [valuations](#def-b1-propositional-logic-valuation) with one [literal](#def-b1-propositional-logic-literal) true.

**Exercise 10.9 ★★.**

Count the [clauses](#def-b1-propositional-logic-literal) of the encoding of [Exercise 10.8](#exo-b1-propositional-logic-8) for $n$ [literals](#def-b1-propositional-logic-literal), and their [literals](#def-b1-propositional-logic-literal). How many [clauses](#def-b1-propositional-logic-literal) say that each of the 7 members of a committee has exactly one of 7 seats and each seat exactly one member?

**Solution of Exercise 10.9.**

One [clause](#def-b1-propositional-logic-literal) of $n$ [literals](#def-b1-propositional-logic-literal) for “at least one”, and one [clause](#def-b1-propositional-logic-literal) of two [literals](#def-b1-propositional-logic-literal) per pair: $n(n - 1)/2 + 1$ [clauses](#def-b1-propositional-logic-literal), with $n + n(n - 1) = n^2$ [literals](#def-b1-propositional-logic-literal). For the committee, 7 groups of members and 7 groups of seats of 7 [literals](#def-b1-propositional-logic-literal) each: $14
\times 22 = 308$ [clauses](#def-b1-propositional-logic-literal).

**Exercise 10.10 ★★★.**

Prove that every formula is equivalent to a formula that uses only the [connectives](#def-b1-propositional-logic-formula) $\neg$ and $\wedge$, by induction on the formula. What is the [size](#def-b1-propositional-logic-size) of the result, as a function of the [size](#def-b1-propositional-logic-size) of the original, if the original has no $\leftrightarrow$? Why does $\leftrightarrow$ cause a problem?

**Solution of Exercise 10.10.**

Define $T$ by induction: $T(p) = p$, $T(\neg\varphi) = \neg T(\varphi)$, $T(\varphi \wedge \psi) = T(\varphi) \wedge
T(\psi)$, $T(\varphi \vee \psi) = \neg(\neg T(\varphi) \wedge \neg T(\psi))$, $T(\varphi \rightarrow \psi) = \neg(T(\varphi)
\wedge \neg T(\psi))$, $T(\varphi \leftrightarrow \psi) = T((\varphi \rightarrow \psi) \wedge (\psi \rightarrow \varphi))$. By induction, $T(\varphi)$ uses only $\neg$ and $\wedge$, and $T(\varphi) \equiv \varphi$: for a variable it is the same formula; for each [connective](#def-b1-propositional-logic-formula), the induction hypothesis gives $T(\varphi) \equiv \varphi$ and $T(\psi) \equiv \psi$, and De Morgan’s laws and the rewriting of implication give the equivalence of the two sides. Without $\leftrightarrow$, each [connective](#def-b1-propositional-logic-formula) adds at most four nodes where it had one, and by induction $\text{size}(T(\varphi))
\leq 4\,\text{size}(\varphi) - 3$. A $\leftrightarrow$ copies $\varphi$ and $\psi$ twice, so nested equivalences double the [size](#def-b1-propositional-logic-size) at each level: the result can be exponential in the [height](#def-b1-propositional-logic-size).

**Exercise 10.11 ★★★.**

Write `quine_units`, Quine’s algorithm with [unit propagation](#def-b1-propositional-logic-unit) before each choice, counting its nodes. Compare its node counts with those of `quine` on the dinner, the [colourings](#def-b1-propositional-logic-colouring) with two and three colours, and the committee of the problem, [satisfiable](#def-b1-propositional-logic-model) and not.

**Solution of Exercise 10.11.**

```python
def quine_units(clauses, stats):
    stats["nodes"] += 1
    forced = set()
    while frozenset() not in clauses:
        unit = next((c for c in clauses if len(c) == 1), None)
        if unit is None:
            break
        (lit,) = unit  # a clause of one literal: that literal must be true
        forced.add(lit)
        clauses = assign(clauses, lit)
    if frozenset() in clauses:
        return None
    if not clauses:
        return forced
    x = min(clauses[0], key=lambda lit: lit.lstrip("~")).lstrip("~")
    for lit in (x, neg(x)):
        model = quine_units(assign(clauses, lit), stats)
        if model is not None:
            return model | forced | {lit}
    return None
```

*Quine’s algorithm with [unit propagation](#def-b1-propositional-logic-unit) code/bachelor-1/10-propositional-logic/listings/quine_units.py*

```
$ python quine_units.py
CNF            clauses    plain  units  satisfiable
dinner               4        6      2  True
2 colours          139      253      3  False
3 colours          189      185     25  True
committee          533     3219      2  True
committee + 1      588   182667     21  False
```

***Output 10.16.** The two algorithms on five sets of [clauses](#def-b1-propositional-logic-literal).*

The two always agree, which the program asserts and the test `tests/test_quine.py` checks on 300 random sets of [clauses](#def-b1-propositional-logic-literal) against brute force. With units, a choice is made only when nothing is forced: on the committee, the units settle almost everything, and a contradiction is found as soon as the forced [literals](#def-b1-propositional-logic-literal) clash.

**Exercise 10.12 ★★★.**

Prove that $\varphi$ is a [tautology](#def-b1-propositional-logic-model) if and only if $\neg\varphi$ is unsatisfiable, and deduce a way to test a [tautology](#def-b1-propositional-logic-model) with Quine’s algorithm. Then prove that [unit propagation](#def-b1-propositional-logic-unit) never turns a [satisfiable](#def-b1-propositional-logic-model) set of [clauses](#def-b1-propositional-logic-literal) into an unsatisfiable one, nor the converse.

**Solution of Exercise 10.12.**

$\varphi$ is a [tautology](#def-b1-propositional-logic-model) when every [valuation](#def-b1-propositional-logic-valuation) makes it true, that is when no [valuation](#def-b1-propositional-logic-valuation) makes $\neg\varphi$ true: when $\neg\varphi$ has no [model](#def-b1-propositional-logic-model). To test $\varphi$, run Quine’s algorithm on a CNF of $\neg\varphi$ (or on Tseitin’s encoding of $\neg\varphi$, which is [equisatisfiable](#def-b1-propositional-logic-equisat)): $\varphi$ is a [tautology](#def-b1-propositional-logic-model) if the answer is “none”, and otherwise the [model](#def-b1-propositional-logic-model) returned is a [valuation](#def-b1-propositional-logic-valuation) where $\varphi$ is false. [Unit propagation](#def-b1-propositional-logic-unit) on a [unit clause](#def-b1-propositional-logic-unit) $\ell$ replaces $S$ by $S_\ell$, $S$ with $\ell$ made true. A [model](#def-b1-propositional-logic-model) of $S$ makes $\ell$ true, since $\ell$ is a [clause](#def-b1-propositional-logic-literal) of $S$, and is then a [model](#def-b1-propositional-logic-model) of $S_\ell$; a [model](#def-b1-propositional-logic-model) of $S_\ell$, with $\ell$ made true, is a [model](#def-b1-propositional-logic-model) of $S$ (as in the proof of [Proposition 10.12](#prop-b1-propositional-logic-quine)). So $S$ and $S_\ell$ are [equisatisfiable](#def-b1-propositional-logic-equisat), and so are the sets before and after each step of propagation.

## 10.7 Problem: Seating the committee

**Problem 10.1.**

Weekend problem — Seating the committee

Seven members of the town’s library committee, Alma, Boris, Chloe, Dmitri, Elena, Farid and Greta (initials A to G), sit in a row of seven seats, numbered 1 to 7. Six rules constrain the seating: Alma sits next to Boris; Chloe does not sit next to Dmitri; Elena sits at an end; Greta, who chairs, sits in the middle seat; Farid sits next to Greta; Chloe sits next to Elena. The variable `C6` says that Chloe sits in seat 6. The program writes the rules as formulas, turns them into [clauses](#def-b1-propositional-logic-literal) by Tseitin’s encoding, adds the [clauses](#def-b1-propositional-logic-literal) of [Exercise 10.8](#exo-b1-propositional-logic-8) for the seats, solves, and checks the answer against all $7! = 5040$ seatings.

```python
GATES = {  # the clauses of t <-> (a op b)
    "&": lambda t, a, b: [[neg(t), a], [neg(t), b], [t, neg(a), neg(b)]],
    "|": lambda t, a, b: [[neg(t), a, b], [t, neg(a)], [t, neg(b)]],
    "->": lambda t, a, b: [[neg(t), neg(a), b], [t, a], [t, neg(b)]],
    "<->": lambda t, a, b: [[neg(t), neg(a), b], [neg(t), a, neg(b)],
                            [t, a, b], [t, neg(a), neg(b)]],
}


def tseitin(f, prefix="t"):
    clauses, names = [], {}

    def literal(g):
        """A literal that is true exactly when g is, given the gate clauses."""
        match g:
            case Var(name):
                return name
            case Not(sub):
                return neg(literal(sub))
            case Bin(op, left, right):
                if g not in names:  # equal subformulas share one variable
                    a, b = literal(left), literal(right)
                    names[g] = t = f"{prefix}{len(names) + 1}"
                    clauses.extend(frozenset(c) for c in GATES[op](t, a, b))
                return names[g]

    clauses.append(frozenset([literal(f)]))  # and the formula itself is true
    return clauses
```

***Listing 10.13.** Tseitin’s encoding: one variable per binary [connective](#def-b1-propositional-logic-formula) code/bachelor-1/10-propositional-logic/listings/tseitin.py*

```python
def at(m, s):  # the variable "member m sits in seat s"
    return Var(f"{m}{s}")


def any_of(fs):
    return reduce(lambda a, b: a | b, fs)


def next_to(x, y):
    return any_of([at(x, s) & any_of([at(y, t) for t in (s - 1, s + 1) if t in SEATS])
                   for s in SEATS])


RULES = {"Alma next to Boris": next_to("A", "B"),
         "Chloe not next to Dmitri": ~next_to("C", "D"),
         "Elena at an end": at("E", 1) | at("E", 7),
         "Greta in the middle": at("G", 4),
         "Farid next to Greta": next_to("F", "G"),
         "Chloe next to Elena": next_to("C", "E")}


def seating_clauses(rules):
    clauses = []
    for m in MEMBERS:
        clauses += exactly_one([f"{m}{s}" for s in SEATS])
    for s in SEATS:
        clauses += exactly_one([f"{m}{s}" for m in MEMBERS])
    for k, f in enumerate(rules.values()):
        clauses += tseitin(f, prefix=f"r{k + 1}t")
    return clauses

```

***Listing 10.14.** The committee’s [clauses](#def-b1-propositional-logic-literal) code/bachelor-1/10-propositional-logic/listings/committee.py*

```
$ python committee.py
Alma next to Boris        size  37  naive CNF  128 clauses  Tseitin  55 clauses
Chloe not next to Dmitri  size  38  naive CNF   12 clauses  Tseitin  55 clauses
Elena at an end           size   3  naive CNF    1 clauses  Tseitin   4 clauses
Greta in the middle       size   1  naive CNF    1 clauses  Tseitin   1 clauses
Farid next to Greta       size  37  naive CNF  128 clauses  Tseitin  55 clauses
Chloe next to Elena       size  37  naive CNF  128 clauses  Tseitin  55 clauses
533 clauses in all
satisfiable: True | nodes: 3219 | checked: True
seating: ABDGFCE
8 seatings out of 5040 obey the rules: ABDGFCE BADGFCE DABGFCE DBAGFCE ECFGABD ECFGBAD ECFGDAB ECFGDBA
with Farid next to Elena: None | nodes: 182667 | by permutations: 0
```

***Output 10.11.** [Sizes](#def-b1-propositional-logic-size), [clause](#def-b1-propositional-logic-literal) counts, a seating, the check, and one rule too many.*

**Part I — The encoding.**

1. How many variables describe a seating? How many [valuations](#def-b1-propositional-logic-valuation) do they have, and how many of them are seatings?
2. Write the rule “Alma sits next to Boris” as `next_to` builds it, for seats 1, 2 and 7 only.
3. Check that the formula of “Alma next to Boris” has [size](#def-b1-propositional-logic-size) 37: count its variables and its [connectives](#def-b1-propositional-logic-formula) .
4. Why is “Chloe not next to Dmitri” of [size](#def-b1-propositional-logic-size) 38?
5. How many [clauses](#def-b1-propositional-logic-literal) do the seat constraints produce, members and seats together?
6. Check the total of 533 [clauses](#def-b1-propositional-logic-literal) .

**Part II — Normal forms and their cost.**

7. The naive CNF of “Alma next to Boris” has 128 [clauses](#def-b1-propositional-logic-literal) . Explain the number $2^7$ by distributivity.
8. Why does the naive CNF of “Chloe not next to Dmitri” have only 12 [clauses](#def-b1-propositional-logic-literal) ? Write two of them.
9. Is the formula of “Alma next to Boris” in DNF? Is “Elena at an end”?
10. With the seat [clauses](#def-b1-propositional-logic-literal) in force, “Alma next to Boris” is equivalent to a formula of fewer [clauses](#def-b1-propositional-logic-literal) : $\bigwedge_s (\neg A_s \vee B_{s-1} \vee B_{s+1})$ . Explain why, and count its [clauses](#def-b1-propositional-logic-literal) .
11. By [Proposition 10.8](#prop-b1-propositional-logic-blowup) , which kind of rule would make the naive CNF unusable?
12. Why do the seat constraints need no Tseitin variable?

**Part III — Tseitin’s encoding.**

13. Check that the three [clauses](#def-b1-propositional-logic-literal) of the `&` gate say $t \leftrightarrow (a \wedge b)$ , by a truth table of eight rows.
14. Why does a negation need no new variable, and why can equal [subformulas](#def-b1-propositional-logic-size) share one?
15. Show that from any [model](#def-b1-propositional-logic-model) of $\varphi$ one obtains a [model](#def-b1-propositional-logic-model) of `tseitin(f)` , by giving each new variable the value of its [subformula](#def-b1-propositional-logic-size) .
16. Show that any [model](#def-b1-propositional-logic-model) of `tseitin(f)` is a [model](#def-b1-propositional-logic-model) of $\varphi$ on the variables of $\varphi$ .
17. Deduce that $\varphi$ and `tseitin(f)` are [equisatisfiable](#def-b1-propositional-logic-equisat) , though not equivalent.
18. Prove *Tseitin’s theorem* : a formula of [size](#def-b1-propositional-logic-size) $m$ has an [equisatisfiable](#def-b1-propositional-logic-equisat) CNF of at most $2m - 1$ [clauses](#def-b1-propositional-logic-literal) , each of at most three [literals](#def-b1-propositional-logic-literal) . Check the bound on the six rules.

**Part IV — Solving and reading back.**

19. Read the seating from the output and check each rule on it.
20. Why do the eight seatings come in pairs? What does each pair have in common?
21. Plain Quine’s algorithm took 3219 nodes. In [Exercise 10.11](#exo-b1-propositional-logic-11) , with [unit propagation](#def-b1-propositional-logic-unit) , it takes 2. Which [unit clause](#def-b1-propositional-logic-unit) starts the propagation?
22. Show by hand, without any search, that adding “Farid sits next to Elena” makes the rules unsatisfiable.
23. Why did the plain algorithm need 182667 nodes to reach the same conclusion?
24. State the named result of the problem, *Tseitin’s theorem* , and the committee’s count.

**Solution of Problem 10.1.**

**1.** 49 variables, $2^{49} \approx 5.6 \times 10^{14}$ [valuations](#def-b1-propositional-logic-valuation), of which $7! = 5040$ describe seatings, one true variable per member and per seat.

**2.** $(A_1 \wedge B_2) \vee (A_2 \wedge (B_1 \vee B_3)) \vee \dots \vee (A_7 \wedge B_6)$.

**3.** Variables: the seven $A_s$, and one neighbour for seats 1 and 7, two for the five others: $7 + 2 + 10 = 19$ leaves. [Connectives](#def-b1-propositional-logic-formula): five inner $\vee$, seven $\wedge$, six outer $\vee$: 18. $19 + 18 = 37$.

**4.** It is the same formula with $\neg$ at the root.

**5.** Each of the 14 groups (7 members, 7 seats) gives 22 [clauses](#def-b1-propositional-logic-literal): 308.

**6.** $308 + 55 + 55 + 4 + 1 + 55 + 55 = 533$.

**7.** The formula is a disjunction of seven conjunctions of two parts, $A_s$ and the part about $B$. A [clause](#def-b1-propositional-logic-literal) of the CNF takes one part from each conjunction: $2^7 = 128$ choices (the parts about $B$ are themselves disjunctions, which merge into the [clause](#def-b1-propositional-logic-literal)).

**8.** The negation of a disjunction is the conjunction of the negations: $\neg(C_s \wedge (D_{s-1} \vee D_{s+1}))
\equiv (\neg C_s \vee \neg D_{s-1}) \wedge (\neg C_s \vee \neg D_{s+1})$, two [clauses](#def-b1-propositional-logic-literal) for each of the five middle seats and one for each end: 12. For instance $\neg C_1 \vee \neg D_2$ and $\neg C_2 \vee \neg D_3$.

**9.** No: the disjunctions $B_{s-1} \vee B_{s+1}$ sit inside the conjunctions. “Elena at an end”, $E_1 \vee
E_7$, is a disjunction of [literals](#def-b1-propositional-logic-literal): in DNF, and in CNF as a single [clause](#def-b1-propositional-logic-literal).

**10.** Alma sits in exactly one seat $s$, and the rule asks that Boris sit next to that one: for every seat, if Alma is there, Boris is beside it, $\neg A_s \vee B_{s-1} \vee B_{s+1}$. Seven [clauses](#def-b1-propositional-logic-literal), equivalent to the rule only together with the seat [clauses](#def-b1-propositional-logic-literal).

**11.** A rule that combines independent alternatives, such as “at least one of the pairs (A, B), (C, D), (E, F) sits side by side”: a disjunction of disjunctions of conjunctions, whose naive CNF multiplies the counts of its parts.

**12.** They are [clauses](#def-b1-propositional-logic-literal) already.

**13.** If $t$ is true, the first two [clauses](#def-b1-propositional-logic-literal) need $a$ and $b$ true, and the third holds. If $t$ is false, the first two hold and the third needs $\neg a \vee \neg b$. So the three [clauses](#def-b1-propositional-logic-literal) hold exactly in the four rows where $t =
a \wedge b$, of the eight rows of $(t, a, b)$.

**14.** The [literal](#def-b1-propositional-logic-literal) $\neg\ell$ is true exactly when $\ell$ is false, so the negation of the [literal](#def-b1-propositional-logic-literal) of $g$ stands for $\neg g$ without any [clause](#def-b1-propositional-logic-literal). Equal [subformulas](#def-b1-propositional-logic-size) have equal [truth values](#def-b1-propositional-logic-valuation) under every [valuation](#def-b1-propositional-logic-valuation), so one variable can stand for both.

**15.** Give each new variable the [truth value](#def-b1-propositional-logic-valuation), under the [model](#def-b1-propositional-logic-model), of the [subformula](#def-b1-propositional-logic-size) it stands for. Each gate’s [clauses](#def-b1-propositional-logic-literal) say $t \leftrightarrow (a \mathbin{\mathrm{op}} b)$, which then holds, and the last [clause](#def-b1-propositional-logic-literal), the [literal](#def-b1-propositional-logic-literal) of $\varphi$, is true because $\varphi$ is.

**16.** By induction on the [subformulas](#def-b1-propositional-logic-size) $g$ of $\varphi$: under a [model](#def-b1-propositional-logic-model) of the [clauses](#def-b1-propositional-logic-literal), the [literal](#def-b1-propositional-logic-literal) of $g$ has the [truth value](#def-b1-propositional-logic-valuation) of $g$. For a variable it is the variable; for a negation, the negated [literal](#def-b1-propositional-logic-literal); for a binary [connective](#def-b1-propositional-logic-formula), the gate’s [clauses](#def-b1-propositional-logic-literal) force $t$ to the value of $a \mathbin{\mathrm{op}} b$. The last [clause](#def-b1-propositional-logic-literal) makes the [literal](#def-b1-propositional-logic-literal) of $\varphi$ true, so $\varphi$ is true.

**17.** By 15, if $\varphi$ is [satisfiable](#def-b1-propositional-logic-model) so are the [clauses](#def-b1-propositional-logic-literal); by 16, the converse. They are not equivalent: they do not have the same variables, and a [model](#def-b1-propositional-logic-model) of $\varphi$ with wrong values for the new variables is not a [model](#def-b1-propositional-logic-model) of the [clauses](#def-b1-propositional-logic-literal).

**18.** *Tseitin’s theorem.* Let $\varphi$ have $L$ leaves, $B$ binary [connectives](#def-b1-propositional-logic-formula) and $N$ negations, so $m =
L + B + N$. A tree whose inner nodes have one or two children has $L = B + 1$ leaves (each binary node adds one branch). The encoding makes at most 4 [clauses](#def-b1-propositional-logic-literal) per binary [connective](#def-b1-propositional-logic-formula) and one for the root: at most $4B + 1 = 2(2B + 1)
- 1 \leq 2(L + B + N) - 1 = 2m - 1$ [clauses](#def-b1-propositional-logic-literal), each of at most three [literals](#def-b1-propositional-logic-literal), and it is computed in one pass over the tree. The six rules: $55 \leq 73$, $55 \leq 75$, $4 \leq 5$, $1 \leq 1$, $55 \leq 73$ and $55 \leq 73$.

**19.** `ABDGFCE`: Alma 1 and Boris 2 are neighbours; Chloe 6 and Dmitri 3 are not; Elena is at seat 7, an end; Greta at 4, the middle; Farid at 5, next to Greta; Chloe at 6, next to Elena.

**20.** The rules do not change when the row is read from the other end (seat $s$ becomes seat $8 - s$): ends, middle and neighbours stay what they are. Each seating and its mirror image form a pair, such as `ABDGFCE` and `ECFGDBA`: the same neighbours, in reverse order.

**21.** The rule “Greta in the middle” is the single variable `G4`, whose encoding is the [unit clause](#def-b1-propositional-logic-unit) `G4`. Propagating it makes Greta absent from every other seat, and every other member absent from seat 4, and so on through the rules.

**22.** Elena sits at an end, which has a single neighbouring seat. Chloe and Farid must both sit next to her, so both in that seat, which holds one member. No seating obeys the rules, and the 5040 permutations confirm it.

**23.** It chooses variables in the order of their names, `A1`, `A2`, …, which say nothing about Chloe, Elena and Farid; the clash appears only deep in each branch, after many useless choices, and every branch must be refuted. [Unit propagation](#def-b1-propositional-logic-unit) follows the consequences of each choice at once and finds the clash in 21 nodes.

**24.** *Tseitin’s theorem.* Every formula of [size](#def-b1-propositional-logic-size) $m$ has an [equisatisfiable](#def-b1-propositional-logic-equisat) CNF of at most $2m - 1$ [clauses](#def-b1-propositional-logic-literal), each of at most three [literals](#def-b1-propositional-logic-literal), computed in one pass over its tree. The committee’s six rules, of [sizes](#def-b1-propositional-logic-size) 37, 38, 3, 1, 37 and 37, give 225 [clauses](#def-b1-propositional-logic-literal) where the bound allows 300; with the 308 seat [clauses](#def-b1-propositional-logic-literal), 533 [clauses](#def-b1-propositional-logic-literal) in all, whose [model](#def-b1-propositional-logic-model) Quine’s algorithm found and the 5040 seatings confirmed.
