Propositional logic: syntax, semantics and entailment
A dense review of propositional logic as a formal language: syntax as trees, semantics through valuations, equivalence, satisfiability, and logical consequence. Conclude with CNF and DNF normal forms and their cost as preparation for SAT.
After this lesson you can
- Represent formulas as syntax trees and evaluate them compositionally under any valuation.
- Decide equivalence, satisfiability, validity, and logical consequence using truth tables and law-based rewriting.
- Use validity–unsatisfiability duality to reduce problems.
- Convert formulas to CNF and DNF and explain why distribution can cause exponential growth.
- Implement an evaluator, equivalence checker, and logical consequence decision procedure from scratch.
Motivation: are these two conditions the same?
A code review shows this change to a service’s guard:
# antes
if not (not es_admin or not verificado) or (es_admin and tiene_token):
permitir()
# después
if es_admin and (verificado or tiene_token):
permitir()
Does the new code do the same as the old? If yes, the change is a refactoring; if not, some combination of values allows a request through one while the other blocks it, a vulnerability or service failure. Trying a few cases by hand cannot decide it. We must treat both conditions as formulas and ask whether they agree on all combinations of variable values.
This is the first formal verification problem, and it appears everywhere:
- Firewall rules or access policies. Each rule is a formula about request attributes. Can a request be treated differently by two rules? Can some rule never activate?
- Specifications. “If the balance is negative, the account is blocked” is a formula. Checking that a design satisfies it, or two specifications do not contradict each other, means reasoning about formulas.
- Circuits and compilers. An optimizer rewriting
!(a && b)as!a || !bmust know the rewrite is a law, not an accident. - Symbolic AI and solvers. A knowledge-based agent stores knowledge as formulas and derives what follows; a SAT solver decides whether constraints have a solution.
This lesson densely reviews propositional logic as a formal language: syntax first (what a formula is as a mathematical object), then semantics (what it means), followed by four questions about formulas: equivalence, validity, satisfiability, and consequence. It ends with normal forms, the input to SAT solvers, and their cost, a first encounter with the exponential wall throughout this module.
Syntax: formulas are trees
Fix a set of propositional variables (or atoms) , each representing a statement that can be true or false: es_admin, “the balance is negative,” “square has a queen.” Syntax says nothing about truth: only which symbol strings are well formed.
“The smallest set” makes this an inductive definition: a string is a formula only if it can be constructed by applying rules finitely many times. Thus is a formula and is not. Greek letters are not formulas: they are metavariables, names in the language used to discuss formulas (the metalanguage) referring to an arbitrary formula.
Each formula is constructed in a definite order, forming a tree: leaves are variables or constants and each internal node is a connective applied to its children. The root connective is the main connective: the last construction rule applied, determining the formula’s type. is a conditional whose antecedent is conjunction and consequent is negation . Subformulas are subtrees.
Unique readability
That a formula “is” a tree is not obvious: a string might be constructed in two ways and correspond to different trees. The definition’s parentheses prevent this.
Proof
First a lemma: no proper prefix of a formula is a formula. Use strong induction on the length of . Suppose is a formula (hence nonempty) that is a proper prefix of formula , and inspect their shared first symbol. If it is a variable or constant, has one symbol and no nonempty proper prefix. If it is , then and with a proper prefix of , contradicting the induction hypothesis for shorter . If it is a parenthesis, and . Formulas and start at the same position, so one prefixes the other; by induction neither can be a proper prefix, hence . The next symbol then agrees, , and the same argument gives . But then , not a proper prefix. Contradiction.
The theorem follows. The first symbol makes the forms exclusive. If as strings, and start at the second position, one prefixes the other, and the lemma forces ; hence and .
∎The practical consequence is enormous: because each formula decomposes uniquely, functions on formulas can be defined by cases according to the grammar, and the definition is well defined. This is structural recursion, and its proof counterpart is structural induction, studied in depth in lesson 7. For example, subformula count (tree nodes) is , , . This lesson’s evaluator, printer, and normal-form converter are all such functions.
Precedence: removing parentheses without changing the tree
Writing every parenthesis is inconvenient, so conventions allow omission while reconstructing the tree:
| Connective | Precedence | Associativity | Example | Read as |
|---|---|---|---|---|
| strongest | ||||
| left | ||||
| left | ||||
| right | ||||
| weakest | right |
This matches arithmetic’s hierarchy ( like minus, like multiplication, like addition), and Python (not > and > or) and C (! > && > ||). Authors disagree whether and have the same precedence, and not all fix associativity for ; when in doubt, use parentheses. The two conventions causing most mistakes are before and right associativity of , both shown in the first interactive.
In , standard reading is ; left to right without precedence it is . With , , the first is 1 and the second 0: different formulas, not two spellings of one. The same happens with : and disagree at .
Semantics: valuations and truth tables
Syntax assigns no meaning. Classical semantics does so as simply as possible: each variable is 1 (true) or 0 (false), and a formula’s value is determined by its variables.
The definition is compositional: each node’s value depends only on its children’s values, not their internal structure. This is what the interactive tree does, and why an evaluator is a postorder traversal linear in formula size. The five connectives in a table:
| 0 | 0 | 1 | 0 | 0 | 1 | 1 |
| 0 | 1 | 1 | 0 | 1 | 1 | 0 |
| 1 | 0 | 0 | 0 | 1 | 0 | 0 |
| 1 | 1 | 0 | 1 | 1 | 1 | 1 |
A valuation assigns values to all variables in , possibly infinitely many. Evaluating one formula needs less:
Proof
By structural induction on . If is a variable, it appears in and by hypothesis; if constant, both values agree by definition. If , variables of are those of , so by induction and . If , variables of and occur in , induction gives and , and is the same function of these two values for and .
∎Thus a formula with variables has only distinct situations, the rows of its truth table. Its full meaning is the function described by that table: its truth function, called a Boolean function in lesson 17. As a table with rows can be filled with 0 and 1 in ways, there are exactly truth functions of variables: 4 of one, 16 of two, 65536 of four. At the end you will see all can be written using .
Material implication and its surprises
The only row where is false is , : this is the material conditional, , meaning “ does not occur without ,” nothing more. Three surprises follow:
- With false antecedent, the conditional is true. “If the user is an administrator, they can delete the database” is satisfied by any system without administrators. It is vacuously true. This is desirable in a specification (the rule requires nothing when inapplicable), but can yield specifications satisfied without saying anything: if a precondition never holds, the specification is trivial.
- It expresses neither cause nor relevance. “If , then Paris is in France” is true because both sides are true. Propositional logic does not see atom content.
- Some tautologies sound absurd. is 1 under every valuation: given any two statements, one “implies” the other. Check the first interactive with the “one implies the other” example.
In code, is not p or q, and also p <= q in Python when both are bool, because False < True. A conditional assertion if p: assert q checks exactly .
Logical equivalence and laws
is an equivalence relation on formulas, and each class is a truth function: infinitely many formulas exist, but only classes with variables. To decide , compare both tables, rows over both sets of variables. Alternatively rewrite with known laws, as in algebra. Basic laws for arbitrary formulas :
| Law | Equivalence |
|---|---|
| Double negation | |
| Commutative and associative | , , and likewise for |
| Idempotence | , |
| De Morgan | , |
| Distributive | , |
| Absorption | , |
| Identity and absorbing | , , , |
| Excluded middle and contradiction | , |
| Conditional | , |
| Contrapositive | |
| Exportation | |
| Biconditional |
Each law is checked with a four- or eight-row table. But laws use metavariables and we apply them at specific locations inside larger formulas. Their legitimacy is a theorem, not obvious.
Write for replacing every occurrence of variable in with formula (on the tree: attach a copy of at each leaf).
Proof
(1) Structural induction on . If , both sides are . If is another variable or constant, substitution does not change it and agree on it. Cases and follow from induction because substitution works child by child and semantics is compositional: , reading as its table.
(2) By (1), and , with and . Since , , so and values agree.
(3) By (1), , with the same on both sides.
∎Thus a rewrite chain where each step applies a law to a subformula proves equivalence. For example, negating a conditional:
Alongside the laws are three rewrites that look like them but are not all laws. From come the converse , inverse , and contrapositive . Only the last is equivalent. Converse and inverse are equivalent to each other (the inverse is the converse’s contrapositive), and both fail at , . Likewise “negating term by term” fails: is not .
The second challenge is the motivating guard, with = es_admin, = verificado, and = tiene_token: De Morgan, two double negations, and factoring prove the refactoring correct without testing a case. Also notice the contrapositive challenge: without the contrapositive rule it takes four steps (conditional definition, commutativity, double negation, and conditional from disjunction). The table’s laws are not independent; almost all derive from a few. Choosing a small set of inference rules deriving all tautologies and only those is the program of deductive systems such as lesson 4’s natural deduction.
Validity, satisfiability, and contradiction
and Peirce’s law are valid; is unsatisfiable; is contingent. Every valid formula is satisfiable, but not conversely, and the three classes (valid, contingent, unsatisfiable) partition all formulas. Negation exchanges them symmetrically:
Proof
(1) , so “ for every ” is the same as “ for every .” (2) Negate (1) applied to , using . (3) exactly when .
∎The duality says one algorithm suffices: a satisfiability decider also decides validity (ask about ) and equivalence (ask about ). A valuation satisfying is a counterexample to validity of . This is what verification tools do: instead of proving a property always holds, they look for an execution violating it; if none exists, the property is proven.
There is an important asymmetry. If is satisfiable, there is a short certificate: the valuation, checked in linear time. If is valid, no short certificate is known in general; the full table has rows. Satisfiability is in NP and validity in coNP, and deciding whether they can be solved in polynomial time is the P versus NP problem.
Logical consequence
Logic’s central question is not whether a formula is true, but whether it follows from others.
A valuation satisfying premises and falsifying conclusion is a counterexample refuting the argument. means no counterexamples exist. Thus (modus ponens), but : , satisfies both premises and falsifies the conclusion. This invalid argument is affirming the consequent, and its cousin is denying the antecedent: .
The cube makes the abstract definition visible. Premises narrow possible situations, and a conclusion follows if true in everything left, even if false outside. More premises mean fewer models and more consequences. If premises leave no models, inclusion holds for any .
Proof
(1) A counterexample to is a satisfying with , meaning : exactly a model of . (3) . (4) is contained in every set. (5) If satisfies , it satisfies by the first hypothesis, hence and, by the second, . The proof of (2) is the final guided exercise.
∎Property (1) is used by automated provers: to prove follows from a knowledge base, add and ask a SAT solver to show no solution exists. This is resolution and DPLL in lesson 19. Property (2) moves premises to the conclusion and back, and with (1) reduces any finite-premise consequence to one satisfiability question: iff is unsatisfiable.
Normal forms: CNF and DNF
Solvers do not accept arbitrary formulas: they want a standard flat form.
is CNF; is DNF; and are both; is neither. A clause is often viewed as a set of literals and a CNF as a set of clauses, since order and repetition change nothing (commutativity, associativity, idempotence). This is the DIMACS format read by SAT solvers.
Proof
Let have variables . For every valuation of those variables, term , where if and if , is 1 exactly at (the minterm of ). The disjunction of for rows where is 1 is 1 exactly on those rows, hence equivalent to ; if none exist, , the empty DNF. For CNF apply this to , , and negate by De Morgan: , with each a clause excluding a row where is 0.
∎An immediate corollary: every truth function, any of the , is expressible with . This connective set is functionally complete, and lesson 17 studies functional completeness generally ( suffices, even one connective). The proof also reveals a problem: the table’s DNF may have up to terms. Is this unavoidable?
Conversion by equivalences
In practice one does not build the table; rewrite in three phases:
- Eliminate and using and .
- Push negations to variables using De Morgan and double negation. The result is negation normal form (NNF): only , , and literals.
- Distribute over (for CNF) or over (for DNF) until flat.
Phase 2 grows size by at most a constant factor. Phase 1 duplicates and at every , already exponential with nested . But the main problem is phase 3: becomes clauses . Sizes multiply.
Proof
The first part is counting: every clause chooses one literal from each of the terms. For the lower bound let be a CNF equivalent to . For each choice consider valuation setting chosen variable of each pair to 0 and the other to 1. Every term is false in , so is too and some clause is false in : all its literals are false in .
That cannot also be false in another with . Otherwise choose with , say and . Then and , so literal is true in and in : contains neither literal of , and for the same reason neither of . Change and in to 1: new valuation satisfies , hence ; but does not see those variables and remains false in , so the CNF is 0 in . This contradicts equivalence. Thus the valuations require distinct clauses.
∎The dual argument says has no equivalent DNF with fewer than terms. No normal form is always short.
With the formula has 119 symbols and its shortest CNF over a billion 30-literal clauses: about 120 GiB at four bytes per literal. SAT solvers avoid the problem by giving up equivalence: the Tseitin transformation introduces a fresh variable per subformula (here one per term suffices, with three clauses forcing and clause ), producing linear-sized CNF not equivalent to the original (it has more variables) but equisatisfiable: it has a model iff the original does. For SAT that is all needed, and lesson 18 develops it.
Implementation from scratch
A complete logic engine fits in a few functions, each structural recursion over the tree. First the tree (one node per grammar rule), a precedence-climbing parser respecting precedence and associativity, evaluator, and printer using minimal parentheses.
from dataclasses import dataclass
import re
@dataclass(frozen=True)
class Var:
name: str
@dataclass(frozen=True)
class Const:
value: bool
@dataclass(frozen=True)
class Not:
a: object
@dataclass(frozen=True)
class Bin:
op: str # 'and', 'or', 'imp', 'iff'
a: object
b: object
PREC = {'iff': 1, 'imp': 2, 'or': 3, 'and': 4}
RIGHT = {'iff': True, 'imp': True, 'or': False, 'and': False}
SYM = {'and': '∧', 'or': '∨', 'imp': '→', 'iff': '↔'}
TOKENS = [(r'\s+', None), (r'<->|↔', 'iff'), (r'->|→', 'imp'), (r'&|∧', 'and'), (r'\||∨', 'or'),
(r'~|¬', 'not'), (r'\(', '('), (r'\)', ')'), (r'⊤', 'top'), (r'⊥', 'bot'), (r'[A-Za-z_]\w*', 'id')]
def tokenize(s):
pos, out = 0, []
while pos < len(s):
for pat, kind in TOKENS:
m = re.match(pat, s[pos:])
if m:
if kind:
out.append((kind, m.group()))
pos += m.end()
break
else:
raise SyntaxError(f"carácter inesperado {s[pos]!r} en la posición {pos}")
return out
def parse(s):
toks, i = tokenize(s), 0
def peek():
return toks[i][0] if i < len(toks) else None
def atom():
nonlocal i
kind = peek()
if kind is None:
raise SyntaxError("falta un operando al final")
i += 1
if kind == 'id':
return Var(toks[i - 1][1])
if kind in ('top', 'bot'):
return Const(kind == 'top')
if kind == 'not':
return Not(atom())
if kind == '(':
f = expr(0)
if peek() != ')':
raise SyntaxError("falta un paréntesis de cierre")
i += 1
return f
raise SyntaxError(f"token inesperado {toks[i - 1][1]!r}")
def expr(min_prec): # escalada de precedencia
nonlocal i
left = atom()
while peek() in PREC and PREC[peek()] >= min_prec:
op = peek()
i += 1
# asociativa a la derecha: el operando derecho admite la misma precedencia
right = expr(PREC[op] if RIGHT[op] else PREC[op] + 1)
left = Bin(op, left, right)
return left
f = expr(0)
if i != len(toks):
raise SyntaxError(f"sobra {toks[i][1]!r}")
return f
def evaluate(f, v):
"""Valor de verdad de f bajo la valoración v (dict nombre -> bool), por recursión estructural."""
match f:
case Var(name):
return v[name]
case Const(value):
return value
case Not(a):
return not evaluate(a, v)
case Bin('and', a, b):
return evaluate(a, v) and evaluate(b, v)
case Bin('or', a, b):
return evaluate(a, v) or evaluate(b, v)
case Bin('imp', a, b):
return (not evaluate(a, v)) or evaluate(b, v)
case Bin('iff', a, b):
return evaluate(a, v) == evaluate(b, v)
raise TypeError(f"no es una fórmula: {f!r}")
def show(f, full=False):
"""Texto con los paréntesis mínimos (o todos, con full=True)."""
def wrap(g, op, side):
s = show(g, full)
if not isinstance(g, Bin):
return s
need = full or PREC[g.op] < PREC[op] or (PREC[g.op] == PREC[op] and side == ('a' if RIGHT[op] else 'b'))
return f"({s})" if need else s
match f:
case Var(name):
return name
case Const(value):
return '⊤' if value else '⊥'
case Not(a):
return '¬' + (f"({show(a, full)})" if isinstance(a, Bin) else show(a, full))
case Bin(op, a, b):
return f"{wrap(a, op, 'a')} {SYM[op]} {wrap(b, op, 'b')}"
def variables(f):
match f:
case Var(name):
return {name}
case Const():
return set()
case Not(a):
return variables(a)
case Bin(_, a, b):
return variables(a) | variables(b)
for s in ["¬p ∨ q ∧ r", "p → q → r", "¬(p ∧ q) ↔ ¬p ∨ ¬q"]:
f = parse(s)
print(f"{s:22s} se lee {show(f, full=True)}")
print()
f = parse("p -> q -> r")
print(f)
print("con p=0, q=1, r=0 vale", evaluate(f, {'p': False, 'q': True, 'r': False}))
print("parse(show(f)) == f:", parse(show(f)) == f)Python match makes structural recursion explicit: one case per grammar rule, each looking only at children. The last line checks a property any minimal-parenthesis printer must satisfy: reparsing its output reproduces the same tree. The parser’s right associativity for depends on one thing: PREC[op] (instead of PREC[op] + 1) in the right operand’s recursive call.
With an evaluator, decision procedures enumerate. itertools.product generates the rows in binary order, and each procedure stops as soon as it finds what it seeks. Validity reduces to satisfiability of negation, as duality says.
import itertools
def valuations(vs):
"""Las 2^n valoraciones de las variables vs, en orden binario (como las filas de una tabla)."""
vs = sorted(vs)
for bits in itertools.product([False, True], repeat=len(vs)):
yield dict(zip(vs, bits))
def truth_table(*fs):
vs = sorted(set().union(*map(variables, fs)))
print(" ".join(vs), "|", " | ".join(show(f) for f in fs))
for v in valuations(vs):
print(" ".join(str(int(v[x])) for x in vs), "|", " | ".join(str(int(evaluate(f, v))) for f in fs))
def satisfiable(f):
"""Una valoración que satisface f, o None. Se detiene en la primera."""
return next((v for v in valuations(variables(f)) if evaluate(f, v)), None)
def valid(f):
"""(True, None) si f es válida; (False, contraejemplo) si no. Dualidad: válida <=> ¬f insatisfacible."""
cex = satisfiable(Not(f))
return cex is None, cex
def equivalent(f, g):
return valid(Bin('iff', f, g))
truth_table(parse("p → q"), parse("¬p ∨ q"), parse("q → p"))
print()
leyes = [
("De Morgan", "¬(p ∧ q)", "¬p ∨ ¬q"),
("distributiva", "p ∨ q ∧ r", "(p ∨ q) ∧ (p ∨ r)"),
("absorción", "p ∨ p ∧ q", "p"),
("contrarrecíproco", "p → q", "¬q → ¬p"),
("exportación", "p ∧ q → r", "p → q → r"),
("recíproco (?)", "p → q", "q → p"),
("De Morgan mal (?)", "¬(p ∧ q)", "¬p ∧ ¬q"),
("→ asociativo (?)", "(p → q) → r", "p → (q → r)"),
]
for nombre, a, b in leyes:
ok, cex = equivalent(parse(a), parse(b))
print(f"{nombre:18s} {a:12s} ≡ {b:20s} {'sí' if ok else 'NO, contraejemplo ' + str({k: int(x) for k, x in cex.items()})}")The three impostors fall to concrete counterexamples. The example is instructive: and disagree at , where the first is and the second vacuously true. Lack of associativity of is why a convention must be fixed.
Now convert to CNF as above: negation normal form and distribution. Represent each clause as a frozenset of literals (nombre, signo), and distribution is literally a Cartesian product of clause lists.
def nnf(f):
"""Forma normal negativa: sin → ni ↔ y con las negaciones solo sobre variables."""
match f:
case Var() | Const():
return f
case Bin('imp', a, b):
return nnf(Bin('or', Not(a), b))
case Bin('iff', a, b):
return nnf(Bin('and', Bin('imp', a, b), Bin('imp', b, a)))
case Bin(op, a, b):
return Bin(op, nnf(a), nnf(b))
case Not(Not(a)):
return nnf(a)
case Not(Bin('and', a, b)):
return Bin('or', nnf(Not(a)), nnf(Not(b)))
case Not(Bin('or', a, b)):
return Bin('and', nnf(Not(a)), nnf(Not(b)))
case Not(Const(value)):
return Const(not value)
case Not(Var()):
return f
case Not(g):
return nnf(Not(nnf(g)))
def cnf_clauses(f):
"""CNF por distribución de una fórmula en NNF, como lista de cláusulas (frozensets de (nombre, signo))."""
match f:
case Var(name):
return [frozenset({(name, True)})]
case Not(Var(name)):
return [frozenset({(name, False)})]
case Const(True):
return []
case Const(False):
return [frozenset()]
case Bin('and', a, b):
return cnf_clauses(a) + cnf_clauses(b)
case Bin('or', a, b):
# (A1 ∧ ... ∧ Am) ∨ (B1 ∧ ... ∧ Bk) ≡ ∧_{i,j} (Ai ∨ Bj): aquí se multiplican los tamaños
return [ca | cb for ca in cnf_clauses(a) for cb in cnf_clauses(b)]
raise ValueError("primero pasa a forma normal negativa")
def from_clauses(cls):
"""Vuelve a construir la fórmula a partir de las cláusulas, para comprobar la equivalencia."""
def lit(name, pos):
return Var(name) if pos else Not(Var(name))
def big(op, xs, empty):
xs = list(xs)
if not xs:
return Const(empty)
out = xs[0]
for x in xs[1:]:
out = Bin(op, out, x)
return out
return big('and', (big('or', (lit(*l) for l in sorted(c)), False) for c in cls), True)
def blowup(n):
"""(x1 ∧ y1) ∨ (x2 ∧ y2) ∨ ... ∨ (xn ∧ yn)"""
return parse(" ∨ ".join(f"(x{i} ∧ y{i})" for i in range(1, n + 1)))
print(show(nnf(parse("¬((p → q) ∧ ¬(r ∨ ¬p))"))))
for n in range(1, 11):
f = blowup(n)
cls = cnf_clauses(nnf(f))
lits = sum(len(c) for c in cls)
check = equivalent(f, from_clauses(cls))[0] if n <= 4 else "-"
print(f"n = {n:2d}: {4 * n - 1:2d} símbolos -> {len(cls):5d} cláusulas, {lits:6d} literales equivalente: {check}")Clauses double with every term, , and literals grow as : with , a 39-symbol formula yields 1024 clauses and 10240 literals. Equivalence checking of the first rows uses equivalent, which traverses the -row table: already 256 for .
That table is the other wall. To see growth, decide validity of a tautology with variables, chained transitivity . Because it is valid, no brute-force decider exits early: it must inspect every row. Then repeat with NumPy, evaluating the full table at once using a Boolean vector per variable.
import time
import numpy as np
def chain(n):
"""((x1 → x2) ∧ ... ∧ (x_{n-1} → x_n)) → (x1 → x_n): válida, así que hay que mirar todas las filas."""
body = " ∧ ".join(f"(x{i} → x{i + 1})" for i in range(1, n))
return parse(f"({body}) → (x1 → x{n})")
print("fuerza bruta con el evaluador recursivo:")
prev = None
for n in range(8, 15, 2):
f = chain(n)
t0 = time.perf_counter()
ok, _ = valid(f)
dt = time.perf_counter() - t0
print(f" n = {n:2d}: válida = {ok}, {2 ** n:6d} filas, {dt * 1e3:8.1f} ms" + (f" (x{dt / prev:.1f} respecto a n - 2)" if prev else ""))
prev = dt
def valid_numpy(f, n):
"""La tabla entera de golpe: cada variable es un vector de 2^n booleanos."""
idx = np.arange(2 ** n, dtype=np.uint32)
cols = {f"x{i + 1}": ((idx >> (n - 1 - i)) & 1).astype(bool) for i in range(n)}
def ev(g):
match g:
case Var(name):
return cols[name]
case Not(a):
return ~ev(a)
case Bin('and', a, b):
return ev(a) & ev(b)
case Bin('or', a, b):
return ev(a) | ev(b)
case Bin('imp', a, b):
return ~ev(a) | ev(b)
return bool(ev(f).all())
print("\nvectorizado con numpy:")
for n in (14, 18, 20, 22):
f = chain(n)
t0 = time.perf_counter()
ok = valid_numpy(f, n)
dt = time.perf_counter() - t0
print(f" n = {n:2d}: válida = {ok}, {2 ** n:8d} filas, {dt * 1e3:8.1f} ms")
anios = dt * 2 ** (60 - 22) / (3600 * 24 * 365)
print(f"\nextrapolando la versión numpy a n = 60: {anios:.1e} años")Every two more variables, time multiplies by four or a little more: the factor 4 in rows and slightly extra because the formula also grows. The vectorized version is tens of times faster, but a constant-factor improvement buys only additional variables: going from 14 to 22 costs the same as a factor 256 gain. Around 20 or 25 variables, the truth table stops being an algorithm and becomes a definition. Real SAT-encoded problems have thousands or millions of variables.
The professional version
sympy.logic function | What it does |
|---|---|
to_cnf(f), to_dnf(f) | conversion by equivalences; with simplify=True, also minimizes |
simplify_logic(f) | simplified CNF or DNF by Quine–McCluskey from the truth table (exponential: above 8 variables it will not try unless force=True) |
satisfiable(f) | a model as dict, or False; uses DPLL with unit propagation |
Implies, Equivalent, And, Or, Not | constructors; also operators &, ~, and >> (Implies), and the vertical bar for disjunction |
import time
from sympy import symbols
from sympy.logic.boolalg import to_cnf, to_dnf, simplify_logic, Implies, Equivalent, And, Or
from sympy.logic.inference import satisfiable as s_satisfiable
p, q, r = symbols('p q r')
print("to_cnf:", to_cnf(Implies(p, q) & Implies(q, r)))
print("to_dnf:", to_dnf(Equivalent(p, q)), " con simplify:", to_dnf(Equivalent(p, q), simplify=True))
print("simplify_logic:", simplify_logic((p & q) | (p & ~q)), " y ", simplify_logic(~(~p | ~q) | (p & r)))
# consecuencia por refutación: Γ ⊨ ψ <=> Γ ∪ {¬ψ} insatisfacible
print("p → q, p ⊨ q: ", s_satisfiable(Implies(p, q) & p & ~q) is False)
print("p ∨ q, ¬p ∨ r ⊨ q ∨ r: ", s_satisfiable((p | q) & (~p | r) & ~(q | r)) is False)
print("p → q, q ⊨ p: contraejemplo", s_satisfiable(Implies(p, q) & q & ~p))
xs, ys = symbols('x1:5'), symbols('y1:5')
g = Or(*[a & b for a, b in zip(xs, ys)])
print("cláusulas de to_cnf(φ_4):", len(to_cnf(g).args))
n = 300
x = symbols(f'x1:{n + 1}')
cadena = And(*[Implies(x[i], x[i + 1]) for i in range(n - 1)])
t0 = time.perf_counter()
res = s_satisfiable(cadena & x[0] & ~x[-1])
print(f"¬(cadena → (x1 → x{n})) con {n} variables: {res}, en {(time.perf_counter() - t0) * 1e3:.0f} ms")Several points to compare with ours. to_dnf of without simplification yields terms such as , contradictions: mechanical distribution like ours. simplify_logic finds minimal forms of two equivalence-hunter challenges, and . Consequences are decided by refutation, exactly as the theorem says. And to_cnf of yields the same 16 clauses as distribution; by the lower-bound theorem, even simplify=True cannot yield fewer.
The last line matters most. Negating the chained tautology with 300 variables is almost CNF (each conditional is clause ), and satisfiable proves in milliseconds that it has no model, while the table would have rows. No magic: unit propagation derives , then , and so on until conflict with , without enumeration. How and when this works is the topic of the SAT problem and lessons 18 and 19. For truly large problems dedicated solvers (MiniSat, CaDiCaL, Kissat) are used via libraries such as PySAT, reading DIMACS CNF.
Common mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 4. What does tell you?
Step 1 of 3. You want to show . How do you proceed?
entails(premises, conclusion): return True if premises ⊨ conclusion, otherwise a dict with a counterexample valuation assigning every variable in premises and conclusion, satisfying every premise, and falsifying the conclusion. Formulas are nested tuples: a variable is a string ('p'), constants are True and False, and nodes are ('not', f), ('and', f, g), ('or', f, g), ('imp', f, g), and ('iff', f, g). You have evaluate and variables already implemented. Return as soon as you find a counterexample: one test has 24 variables.from itertools import product
def evaluate(f, v):
if isinstance(f, bool):
return f
if isinstance(f, str):
return v[f]
op = f[0]
if op == 'not':
return not evaluate(f[1], v)
a, b = evaluate(f[1], v), evaluate(f[2], v)
return {'and': a and b, 'or': a or b, 'imp': (not a) or b, 'iff': a == b}[op]
def variables(f):
if isinstance(f, bool):
return set()
if isinstance(f, str):
return {f}
return set().union(*(variables(g) for g in f[1:]))
def entails(premises, conclusion):
"""True si premises ⊨ conclusion; si no, un dict con una valoración contraejemplo."""
# tu código: recorre las valoraciones de todas las variables y sal en el primer contraejemplo
return TrueSummary
- Syntax is an inductive grammar; unique readability makes each formula a tree with a main connective and allows functions and proofs by structural recursion and induction. Precedence (, with right-associative) only omits parentheses.
- A valuation assigns 0 or 1 to variables and extends compositionally. A formula with variables has rows and there are truth functions. The material conditional is false only with true antecedent and false consequent.
- iff they agree under every valuation. Laws (De Morgan, distributive, absorption, contrapositive…) apply in any context to arbitrary formulas by substitution; converse and inverse are not laws.
- is valid iff is unsatisfiable, and iff is valid. Satisfiable has a short certificate (NP); valid generally does not (coNP).
- means : no counterexamples. It is equivalent to being unsatisfiable, and deduction moves a premise into the conclusion as antecedent: iff . Everything follows from inconsistent premises.
- Every formula has equivalent CNF and DNF, but distribution can be exponential and for no equivalent CNF has fewer than clauses. Solvers use linear equisatisfiable Tseitin.