Module contents
Lesson 1 of 22Review 75 min

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 || !b must 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) P={p,q,r,… }\mathcal{P} = \{p, q, r, \dots\}, each representing a statement that can be true or false: es_admin, “the balance is negative,” “square (3,5)(3, 5) 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 ((p∧q)→¬r)((p \land q) \to \lnot r) is a formula and p∧→qp \land \to q is not. Greek letters φ,ψ,χ\varphi, \psi, \chi 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. ((p∧q)→¬r)((p \land q) \to \lnot r) is a conditional whose antecedent is conjunction (p∧q)(p \land q) and consequent is negation ¬r\lnot r. 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 φ\varphi. Suppose φ′\varphi' is a formula (hence nonempty) that is a proper prefix of formula φ\varphi, and inspect their shared first symbol. If it is a variable or constant, φ\varphi has one symbol and no nonempty proper prefix. If it is ¬\lnot, then φ=¬α\varphi = \lnot\alpha and φ′=¬α′\varphi' = \lnot\alpha' with α′\alpha' a proper prefix of α\alpha, contradicting the induction hypothesis for shorter α\alpha. If it is a parenthesis, φ=(α∘β)\varphi = (\alpha \circ \beta) and φ′=(α′∘′β′)\varphi' = (\alpha' \circ' \beta'). Formulas α\alpha and α′\alpha' start at the same position, so one prefixes the other; by induction neither can be a proper prefix, hence α=α′\alpha = \alpha'. The next symbol then agrees, ∘=∘′\circ = \circ', and the same argument gives β=β′\beta = \beta'. But then φ′=φ\varphi' = \varphi, not a proper prefix. Contradiction.

The theorem follows. The first symbol makes the forms exclusive. If (α∘β)=(α′∘′β′)(\alpha \circ \beta) = (\alpha' \circ' \beta') as strings, α\alpha and α′\alpha' start at the second position, one prefixes the other, and the lemma forces α=α′\alpha = \alpha'; hence ∘=∘′\circ = \circ' and β=β′\beta = \beta'.

∎

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 tam⁡(p)=1\operatorname{tam}(p) = 1, tam⁡(¬φ)=1+tam⁡(φ)\operatorname{tam}(\lnot\varphi) = 1 + \operatorname{tam}(\varphi), tam⁡((φ∘ψ))=1+tam⁡(φ)+tam⁡(ψ)\operatorname{tam}((\varphi \circ \psi)) = 1 + \operatorname{tam}(\varphi) + \operatorname{tam}(\psi). 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:

ConnectivePrecedenceAssociativityExampleRead as
¬\lnotstrongest¬p∧q\lnot p \land q(¬p)∧q(\lnot p) \land q
∧\landleftp∧q∨rp \land q \lor r(p∧q)∨r(p \land q) \lor r
∨\lorleftp∨q→rp \lor q \to r(p∨q)→r(p \lor q) \to r
→\torightp→q→rp \to q \to rp→(q→r)p \to (q \to r)
↔\leftrightarrowweakestrightp↔q∨rp \leftrightarrow q \lor rp↔(q∨r)p \leftrightarrow (q \lor r)

This matches arithmetic’s hierarchy (¬\lnot like minus, ∧\land like multiplication, ∨\lor like addition), and Python (not > and > or) and C (! > && > ||). Authors disagree whether ∧\land and ∨\lor have the same precedence, and not all fix associativity for →\to; when in doubt, use parentheses. The two conventions causing most mistakes are ∧\land before ∨\lor and right associativity of →\to, both shown in the first interactive.

InteractiveThe formula as a tree evaluated bottom up
With all parentheses: ¬p∨(q∧r)\lnot p \lor (q \land r)
p0¬1q1r0∧0∨1
is 1is 0just changed
Selected subformula: ¬p∨q∧r\lnot p \lor q \land r, with value 1: calculated only from its children’s values.
fully evaluated
Valuation
Main connective∨ (disjunction)
Formula value1 (true)
Subformulas (nodes) and height6 and 2
Table rows where value is 15 of 8
Enter a formula or choose an example. The tree is its syntax and the root its main connective. Tap a leaf to change that variable's value: changing nodes light up and always form paths rising from that variable's leaves, stopping at the first unchanged node. Replay evaluation step by step: each node is computed only from its children. Then enable reading without precedence: the same text gives another tree, and the widget finds a valuation where they disagree. Try De Morgan's law and Peirce's law: can any valuation make the root false?

In ¬p∨q∧r\lnot p \lor q \land r, standard reading is ¬p∨(q∧r)\lnot p \lor (q \land r); left to right without precedence it is (¬p∨q)∧r(\lnot p \lor q) \land r. With p=0p = 0, q=1q = 1, r=0r = 0 the first is 1 and the second 0: different formulas, not two spellings of one. The same happens with p→q→rp \to q \to r: p→(q→r)p \to (q \to r) and (p→q)→r(p \to q) \to r disagree at p=q=r=0p = q = r = 0.

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:

ppqq¬p\lnot pp∧qp \land qp∨qp \lor qp→qp \to qp↔qp \leftrightarrow q
0010011
0110110
1000100
1101111

A valuation assigns values to all variables in P\mathcal{P}, possibly infinitely many. Evaluating one formula needs less:

Proof

By structural induction on φ\varphi. If φ\varphi is a variable, it appears in φ\varphi and v(φ)=w(φ)v(\varphi) = w(\varphi) by hypothesis; if constant, both values agree by definition. If φ=¬α\varphi = \lnot\alpha, variables of α\alpha are those of φ\varphi, so v(α)=w(α)v(\alpha) = w(\alpha) by induction and v(φ)=1−v(α)=1−w(α)=w(φ)v(\varphi) = 1 - v(\alpha) = 1 - w(\alpha) = w(\varphi). If φ=(α∘β)\varphi = (\alpha \circ \beta), variables of α\alpha and β\beta occur in φ\varphi, induction gives v(α)=w(α)v(\alpha) = w(\alpha) and v(β)=w(β)v(\beta) = w(\beta), and φ\varphi is the same function of these two values for vv and ww.

∎

Thus a formula with nn variables has only 2n2^n distinct situations, the rows of its truth table. Its full meaning is the function {0,1}n→{0,1}\{0, 1\}^n \to \{0, 1\} described by that table: its truth function, called a Boolean function in lesson 17. As a table with 2n2^n rows can be filled with 0 and 1 in 22n2^{2^n} ways, there are exactly 22n2^{2^n} truth functions of nn variables: 4 of one, 16 of two, 65536 of four. At the end you will see all can be written using ¬,∧,∨\lnot, \land, \lor.

Material implication and its surprises

The only row where p→qp \to q is false is p=1p = 1, q=0q = 0: this is the material conditional, p→q≡¬p∨qp \to q \equiv \lnot p \lor q, meaning “pp does not occur without qq,” nothing more. Three surprises follow:

  1. 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.
  2. It expresses neither cause nor relevance. “If 2+2=42 + 2 = 4, then Paris is in France” is true because both sides are true. Propositional logic does not see atom content.
  3. Some tautologies sound absurd. (p→q)∨(q→p)(p \to q) \lor (q \to p) 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, p→qp \to q 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 p→qp \to q.

Logical equivalence and laws

≡\equiv is an equivalence relation on formulas, and each class is a truth function: infinitely many formulas exist, but only 22n2^{2^n} classes with nn variables. To decide φ≡ψ\varphi \equiv \psi, compare both tables, 2n2^n rows over both sets of variables. Alternatively rewrite with known laws, as in algebra. Basic laws for arbitrary formulas φ,ψ,χ\varphi, \psi, \chi:

LawEquivalence
Double negation¬¬φ≡φ\lnot\lnot\varphi \equiv \varphi
Commutative and associativeφ∧ψ≡ψ∧φ\varphi \land \psi \equiv \psi \land \varphi,  (φ∧ψ)∧χ≡φ∧(ψ∧χ)\ (\varphi \land \psi) \land \chi \equiv \varphi \land (\psi \land \chi), and likewise for ∨\lor
Idempotenceφ∧φ≡φ\varphi \land \varphi \equiv \varphi,  φ∨φ≡φ\ \varphi \lor \varphi \equiv \varphi
De Morgan¬(φ∧ψ)≡¬φ∨¬ψ\lnot(\varphi \land \psi) \equiv \lnot\varphi \lor \lnot\psi,  ¬(φ∨ψ)≡¬φ∧¬ψ\ \lnot(\varphi \lor \psi) \equiv \lnot\varphi \land \lnot\psi
Distributiveφ∧(ψ∨χ)≡(φ∧ψ)∨(φ∧χ)\varphi \land (\psi \lor \chi) \equiv (\varphi \land \psi) \lor (\varphi \land \chi),  φ∨(ψ∧χ)≡(φ∨ψ)∧(φ∨χ)\ \varphi \lor (\psi \land \chi) \equiv (\varphi \lor \psi) \land (\varphi \lor \chi)
Absorptionφ∨(φ∧ψ)≡φ\varphi \lor (\varphi \land \psi) \equiv \varphi,  φ∧(φ∨ψ)≡φ\ \varphi \land (\varphi \lor \psi) \equiv \varphi
Identity and absorbingφ∧⊤≡φ\varphi \land \top \equiv \varphi,  φ∨⊥≡φ\ \varphi \lor \bot \equiv \varphi,  φ∧⊥≡⊥\ \varphi \land \bot \equiv \bot,  φ∨⊤≡⊤\ \varphi \lor \top \equiv \top
Excluded middle and contradictionφ∨¬φ≡⊤\varphi \lor \lnot\varphi \equiv \top,  φ∧¬φ≡⊥\ \varphi \land \lnot\varphi \equiv \bot
Conditionalφ→ψ≡¬φ∨ψ\varphi \to \psi \equiv \lnot\varphi \lor \psi,  ¬(φ→ψ)≡φ∧¬ψ\ \lnot(\varphi \to \psi) \equiv \varphi \land \lnot\psi
Contrapositiveφ→ψ≡¬ψ→¬φ\varphi \to \psi \equiv \lnot\psi \to \lnot\varphi
Exportation(φ∧ψ)→χ≡φ→(ψ→χ)(\varphi \land \psi) \to \chi \equiv \varphi \to (\psi \to \chi)
Biconditionalφ↔ψ≡(φ→ψ)∧(ψ→φ)\varphi \leftrightarrow \psi \equiv (\varphi \to \psi) \land (\psi \to \varphi)

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 χ[θ/p]\chi[\theta/p] for replacing every occurrence of variable pp in χ\chi with formula θ\theta (on the tree: attach a copy of θ\theta at each pp leaf).

Proof

(1) Structural induction on χ\chi. If χ=p\chi = p, both sides are v(θ)v(\theta). If χ\chi is another variable or constant, substitution does not change it and v,v′v, v' agree on it. Cases ¬α\lnot\alpha and (α∘β)(\alpha \circ \beta) follow from induction because substitution works child by child and semantics is compositional: v((α∘β)[θ/p])=v(α[θ/p])∘v(β[θ/p])=v′(α)∘v′(β)=v′(α∘β)v((\alpha \circ \beta)[\theta/p]) = v(\alpha[\theta/p]) \circ v(\beta[\theta/p]) = v'(\alpha) \circ v'(\beta) = v'(\alpha \circ \beta), reading ∘\circ as its table.

(2) By (1), v(χ[φ/p])=v1(χ)v(\chi[\varphi/p]) = v_1(\chi) and v(χ[ψ/p])=v2(χ)v(\chi[\psi/p]) = v_2(\chi), with v1(p)=v(φ)v_1(p) = v(\varphi) and v2(p)=v(ψ)v_2(p) = v(\psi). Since φ≡ψ\varphi \equiv \psi, v(φ)=v(ψ)v(\varphi) = v(\psi), so v1=v2v_1 = v_2 and values agree.

(3) By (1), v(φ[θ/p])=v′(φ)=v′(ψ)=v(ψ[θ/p])v(\varphi[\theta/p]) = v'(\varphi) = v'(\psi) = v(\psi[\theta/p]), with the same v′v' on both sides.

∎

Thus a rewrite chain where each step applies a law to a subformula proves equivalence. For example, negating a conditional:

¬(p→q)\lnot(p \to q)
Start: when does a conditional fail?
1/4

Alongside the laws are three rewrites that look like them but are not all laws. From p→qp \to q come the converse q→pq \to p, inverse ¬p→¬q\lnot p \to \lnot q, and contrapositive ¬q→¬p\lnot q \to \lnot p. Only the last is equivalent. Converse and inverse are equivalent to each other (the inverse is the converse’s contrapositive), and both fail at p=0p = 0, q=1q = 1. Likewise “negating term by term” fails: ¬(p∧q)\lnot(p \land q) is not ¬p∧¬q\lnot p \land \lnot q.

InteractiveEquivalence hunter
Convert ¬(p→q)\lnot(p \to q) to a formula without →\to, with negations next to variables.
φ=\varphi =¬(p→q)\lnot(p \to q)ψ=\psi =¬\lnotpp→\to¬\lnotqqtargetp∧¬qp \land \lnot q
pqφ\varphiψ\psi
0001✗
0100
1011
1101✗
Rewrite chain
  1. ¬(p→q)\lnot(p \to q)(start)
  2. ¬p→¬q\lnot p \to \lnot q(Negate both sides of a conditional: not a law)
Applicable rules
to subformula ¬p→¬q\lnot p \to \lnot q
Steps1 (1 not laws)
Rows where they differ2 of 4
φ≡ψ\varphi \equiv \psi?no
Counterexamplep = 0, q = 0
«Negate both sides of a conditional» is not a law: with p = 0, q = 0 the formula was 0 before the step and 1 afterward.
At the top are starting formula φ\varphi and formula ψ\psi being rewritten. Tap a subformula of ψ\psi and apply a matching rule. Beware: not all are laws. The table compares φ\varphi and ψ\psi under every valuation, and an invalid rule immediately reveals itself in a red row with the valuation where the value changes. The initial challenge already has a tempting step applied: undo it and reach the goal using laws. Then try other challenges and free mode with your own formulas.

The second challenge is the motivating guard, with pp = es_admin, qq = verificado, and rr = 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

p∨¬pp \lor \lnot p and Peirce’s law ((p→q)→p)→p((p \to q) \to p) \to p are valid; p∧¬pp \land \lnot p is unsatisfiable; p→qp \to q 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) v(¬φ)=1−v(φ)v(\lnot\varphi) = 1 - v(\varphi), so “v(φ)=1v(\varphi) = 1 for every vv” is the same as “v(¬φ)=0v(\lnot\varphi) = 0 for every vv.” (2) Negate (1) applied to ¬φ\lnot\varphi, using ¬¬φ≡φ\lnot\lnot\varphi \equiv \varphi. (3) v(φ↔ψ)=1v(\varphi \leftrightarrow \psi) = 1 exactly when v(φ)=v(ψ)v(\varphi) = v(\psi).

∎

The duality says one algorithm suffices: a satisfiability decider also decides validity (ask about ¬φ\lnot\varphi) and equivalence (ask about ¬(φ↔ψ)\lnot(\varphi \leftrightarrow \psi)). A valuation satisfying ¬φ\lnot\varphi is a counterexample to validity of φ\varphi. 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 φ\varphi is satisfiable, there is a short certificate: the valuation, checked in linear time. If φ\varphi is valid, no short certificate is known in general; the full table has 2n2^n 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. Γ⊨ψ\Gamma \models \psi means no counterexamples exist. Thus p→q,p⊨qp \to q, p \models q (modus ponens), but p→q,q⊭pp \to q, q \not\models p: p=0p = 0, q=1q = 1 satisfies both premises and falsifies the conclusion. This invalid argument is affirming the consequent, and its cousin is denying the antecedent: p→q,¬p⊭¬qp \to q, \lnot p \not\models \lnot q.

InteractiveConsequence as inclusion of models
{p→q, q}⊭p\{p \to q,\ q\} \not\models p
p →q ↑r ↗000001010✗011✗100101110111
model of the premises counterexample label: values of p, q, r; squares: premises (filled = true); diamond: conclusion
Refutation: \{p \to q,\ q,\ \lnot p\}$ has models (red vertices), so the consequence fails.
Premises Γ\Gamma (leave extras blank)
Conclusion ψ\psi
Models of Γ\Gamma4 of 8
Models of the conclusion4 of 8
Counterexamples2
Γ∪{¬ψ}\Gamma \cup \{\lnot\psi\} issatisfiable
Does not follow. Counterexample: p=0p = 0, q=1q = 1, r=0r = 0.
The eight valuations of p,q,rp, q, r are vertices of the cube {0,1}3\{0, 1\}^3, connected when they differ in one variable. At each vertex colored squares indicate satisfied premises and the diamond indicates whether the conclusion holds. Filled vertices model the premises; red ones are counterexamples. Γ⊨ψ\Gamma \models \psi iff no vertex is red. Explore the listed arguments: modus ponens and transitivity hold, affirming the consequent and denying the antecedent do not. See what happens with inconsistent premises. Finally enable the deduction theorem: verdict and red vertices remain unchanged.

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 ∅⊆Mod⁡(ψ)\emptyset \subseteq \operatorname{Mod}(\psi) holds for any ψ\psi.

Proof

(1) A counterexample to Γ⊨ψ\Gamma \models \psi is a vv satisfying Γ\Gamma with v(ψ)=0v(\psi) = 0, meaning v(¬ψ)=1v(\lnot\psi) = 1: exactly a model of Γ∪{¬ψ}\Gamma \cup \{\lnot\psi\}. (3) Mod⁡(Δ)⊆Mod⁡(Γ)⊆Mod⁡(ψ)\operatorname{Mod}(\Delta) \subseteq \operatorname{Mod}(\Gamma) \subseteq \operatorname{Mod}(\psi). (4) Mod⁡(Γ)=∅\operatorname{Mod}(\Gamma) = \emptyset is contained in every set. (5) If vv satisfies Γ\Gamma, it satisfies φ\varphi by the first hypothesis, hence Γ∪{φ}\Gamma \cup \{\varphi\} and, by the second, ψ\psi. The proof of (2) is the final guided exercise.

∎

Property (1) is used by automated provers: to prove ψ\psi follows from a knowledge base, add ¬ψ\lnot\psi 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: φ1,…,φk⊨ψ\varphi_1, \dots, \varphi_k \models \psi iff φ1∧⋯∧φk∧¬ψ\varphi_1 \land \cdots \land \varphi_k \land \lnot\psi is unsatisfiable.

Normal forms: CNF and DNF

Solvers do not accept arbitrary formulas: they want a standard flat form.

(p∨¬q)∧(¬p∨r)∧q(p \lor \lnot q) \land (\lnot p \lor r) \land q is CNF; (p∧q)∨(¬p∧r)(p \land q) \lor (\lnot p \land r) is DNF; p∧qp \land q and ¬p\lnot p are both; ¬(p∨q)\lnot(p \lor q) 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 φ\varphi have variables p1,…,pnp_1, \dots, p_n. For every valuation vv of those variables, term tv=ℓ1∧⋯∧ℓnt_v = \ell_1 \land \cdots \land \ell_n, where ℓi=pi\ell_i = p_i if v(pi)=1v(p_i) = 1 and ℓi=¬pi\ell_i = \lnot p_i if v(pi)=0v(p_i) = 0, is 1 exactly at vv (the minterm of vv). The disjunction of tvt_v for rows where φ\varphi is 1 is 1 exactly on those rows, hence equivalent to φ\varphi; if none exist, φ≡⊥\varphi \equiv \bot, the empty DNF. For CNF apply this to ¬φ\lnot\varphi, ¬φ≡t1∨⋯∨tm\lnot\varphi \equiv t_1 \lor \cdots \lor t_m, and negate by De Morgan: φ≡¬t1∧⋯∧¬tm\varphi \equiv \lnot t_1 \land \cdots \land \lnot t_m, with each ¬tj\lnot t_j a clause excluding a row where φ\varphi is 0.

∎

An immediate corollary: every truth function, any of the 22n2^{2^n}, is expressible with ¬,∧,∨\lnot, \land, \lor. This connective set is functionally complete, and lesson 17 studies functional completeness generally ({¬,∧}\{\lnot, \land\} suffices, even one connective). The proof also reveals a problem: the table’s DNF may have up to 2n2^n terms. Is this unavoidable?

Conversion by equivalences

In practice one does not build the table; rewrite in three phases:

  1. Eliminate ↔\leftrightarrow and →\to using φ↔ψ≡(φ→ψ)∧(ψ→φ)\varphi \leftrightarrow \psi \equiv (\varphi \to \psi) \land (\psi \to \varphi) and φ→ψ≡¬φ∨ψ\varphi \to \psi \equiv \lnot\varphi \lor \psi.
  2. Push negations to variables using De Morgan and double negation. The result is negation normal form (NNF): only ∧\land, ∨\lor, and literals.
  3. Distribute ∨\lor over ∧\land (for CNF) or ∧\land over ∨\lor (for DNF) until flat.

Phase 2 grows size by at most a constant factor. Phase 1 duplicates φ\varphi and ψ\psi at every ↔\leftrightarrow, already exponential with nested ↔\leftrightarrow. But the main problem is phase 3: (A1∧⋯∧Am)∨(B1∧⋯∧Bk)(A_1 \land \cdots \land A_m) \lor (B_1 \land \cdots \land B_k) becomes m⋅km \cdot k clauses Ai∨BjA_i \lor B_j. Sizes multiply.

Proof

The first part is counting: every clause chooses one literal from each of the nn terms. For the lower bound let C1∧⋯∧CmC_1 \land \cdots \land C_m be a CNF equivalent to φn\varphi_n. For each choice s=(s1,…,sn)s = (s_1, \dots, s_n) consider valuation asa_s setting chosen variable sis_i of each pair to 0 and the other to 1. Every term xi∧yix_i \land y_i is false in asa_s, so φn\varphi_n is too and some clause CC is false in asa_s: all its literals are false in asa_s.

That CC cannot also be false in another ata_t with t≠st \neq s. Otherwise choose ii with si≠tis_i \neq t_i, say si=xis_i = x_i and ti=yit_i = y_i. Then as(xi)=0a_s(x_i) = 0 and at(xi)=1a_t(x_i) = 1, so literal xix_i is true in ata_t and ¬xi\lnot x_i in asa_s: CC contains neither literal of xix_i, and for the same reason neither of yiy_i. Change xix_i and yiy_i in asa_s to 1: new valuation bb satisfies xi∧yix_i \land y_i, hence φn\varphi_n; but CC does not see those variables and remains false in bb, so the CNF is 0 in bb. This contradicts equivalence. Thus the 2n2^n valuations asa_s require 2n2^n distinct clauses.

∎

The dual argument says (x1∨y1)∧⋯∧(xn∨yn)(x_1 \lor y_1) \land \cdots \land (x_n \lor y_n) has no equivalent DNF with fewer than 2n2^n terms. No normal form is always short.

InteractiveCNF explosion by distribution
φ4=(x1∧y1)∨(x2∧y2)∨(x3∧y3)∨(x4∧y4)\varphi_{4} = (x_{1} \land y_{1}) \lor (x_{2} \land y_{2}) \lor (x_{3} \land y_{3}) \lor (x_{4} \land y_{4})
After distributing the first 4 terms: 16 clauses of 4 literals. Each column is a clause; each row chooses between xix_i and yiy_i.
1234
the clause contains xix_ithe clause contains yiy_i
4 of 4 terms
Size versus nn, logarithmic scale
  • CNF by distribution: 2n2^n clauses
  • literals of that CNF: n 2nn\,2^n
  • Tseitin: 3n+13n + 1 clauses
  • Tseitin literals: 8n8n
With n=4n = 4: 1616 clauses versus 1313.
4
Conversion
Clauses by distribution16
Literals by distribution64
Memory at 4 bytes per literal256 B
Clauses with Tseitin13 (with 4 new variables)
Size ratio (literals)2
Replay distribution of φn\varphi_n term by term. Each matrix column is a clause and each row says whether that clause takes xix_i or yiy_i: adding a term splits every clause in two and doubles the matrix. Increase nn with the slider and inspect the logarithmic graph: CNF clauses follow a straight line of slope log⁡2\log 2, the exponential, while Tseitin transformation grows linearly. Switch to Tseitin view to see its clauses and why it is equisatisfiable rather than equivalent.

With n=30n = 30 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 ziz_i per term suffices, with three clauses forcing zi↔(xi∧yi)z_i \leftrightarrow (x_i \land y_i) and clause z1∨⋯∨znz_1 \lor \cdots \lor z_n), 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.

[ ]AST, parser, and evaluatorBrowser
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 →\to 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 2n2^n 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.

[ ]Truth tables and decision proceduresBrowser
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 →\to example is instructive: (p→q)→r(p \to q) \to r and p→(q→r)p \to (q \to r) disagree at p=q=r=0p = q = r = 0, where the first is 1→0=01 \to 0 = 0 and the second vacuously true. Lack of associativity of →\to 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.

[ ]CNF by distribution and its sizeBrowser
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, 2n2^n, and literals grow as n 2nn\,2^n: with n=10n = 10, a 39-symbol formula yields 1024 clauses and 10240 literals. Equivalence checking of the first rows uses equivalent, which traverses the 22n2^{2n}-row table: already 256 for n=4n = 4.

That table is the other wall. To see growth, decide validity of a tautology with nn variables, chained transitivity ((x1→x2)∧⋯∧(xn−1→xn))→(x1→xn)\big((x_1 \to x_2) \land \cdots \land (x_{n-1} \to x_n)\big) \to (x_1 \to x_n). 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 2n2^n Boolean vector per variable.

[ ]The exponential wallBrowser
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 cc buys only log⁡2c\log_2 c 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 functionWhat 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, Notconstructors; also operators &, ~, and >> (Implies), and the vertical bar for disjunction
[ ]sympy.logic compared with oursBrowser
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 p↔qp \leftrightarrow q without simplification yields terms such as p∧¬pp \land \lnot p, contradictions: mechanical distribution like ours. simplify_logic finds minimal forms of two equivalence-hunter challenges, pp and p∧(q∨r)p \land (q \lor r). Consequences are decided by refutation, exactly as the theorem says. And to_cnf of φ4\varphi_4 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 xi→xi+1x_i \to x_{i+1} is clause ¬xi∨xi+1\lnot x_i \lor x_{i+1}), and satisfiable proves in milliseconds that it has no model, while the table would have 23002^{300} rows. No magic: unit propagation derives x1=1x_1 = 1, then x2=1x_2 = 1, and so on until conflict with ¬x300\lnot x_{300}, 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

QuizEquivalents of the conditional
Which formulas are equivalent to p→qp \to q?

More than one answer may be correct.

NumericHow many truth functions?
How many distinct truth functions have 3 variables? That is, how many classes of mutually nonequivalent formulas use variables among p,q,rp, q, r?
NumericCounting models
How many valuations of p,q,rp, q, r satisfy (p→q)∧(q→r)(p \to q) \land (q \to r)?
QuizSatisfiable, valid, and negated
If φ\varphi is satisfiable, what can you assert about ¬φ\lnot\varphi?
QuizThe resolution pattern
Is it true that p∨q, ¬p∨r⊨q∨rp \lor q,\ \lnot p \lor r \models q \lor r?
QuizLanguage and metalanguage
Which statements are true?

More than one answer may be correct.

NumericThe shortest CNF
What is the minimum number of clauses in a CNF equivalent to (x1∧y1)∨(x2∧y2)∨⋯∨(x5∧y5)(x_1 \land y_1) \lor (x_2 \land y_2) \lor \cdots \lor (x_5 \land y_5)?
ProofConditional transitivity in two ways
Prove: Prove {p→q, q→r}⊨p→r\{p \to q,\ q \to r\} \models p \to r, first semantically and then by a chain of equivalences.
0
First method: suppose there is a counterexample, a valuation vv satisfying both premises with v(p→r)=0v(p \to r) = 0.

Step 1 of 4. What does v(p→r)=0v(p \to r) = 0 tell you?

ProofThe semantic deduction theorem
Prove: For every set of formulas Γ\Gamma and formulas φ,ψ\varphi, \psi: Γ∪{φ}⊨ψ\Gamma \cup \{\varphi\} \models \psi iff Γ⊨φ→ψ\Gamma \models \varphi \to \psi.
0
Prove the two directions separately. Start forward: assume Γ∪{φ}⊨ψ\Gamma \cup \{\varphi\} \models \psi and take a valuation vv satisfying Γ\Gamma.

Step 1 of 3. You want to show v(φ→ψ)=1v(\varphi \to \psi) = 1. How do you proceed?

CodeA consequence decider with counterexample
Implement 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 True
Shift+Enter to run

Summary

Key idea
A formula is a tree, its meaning a truth function computed bottom up, and the four questions (equivalence, validity, satisfiability, consequence) reduce to one: does this formula have a model? Answering by a table costs 2n2^n, and conversion to an equivalent normal form can cost as much.
  • 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 (¬>∧>∨>→>↔\lnot > \land > \lor > \to > \leftrightarrow, with →\to right-associative) only omits parentheses.
  • A valuation assigns 0 or 1 to variables and extends compositionally. A formula with nn variables has 2n2^n rows and there are 22n2^{2^n} truth functions. The material conditional is false only with true antecedent and false consequent.
  • φ≡ψ\varphi \equiv \psi 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.
  • φ\varphi is valid iff ¬φ\lnot\varphi is unsatisfiable, and φ≡ψ\varphi \equiv \psi iff φ↔ψ\varphi \leftrightarrow \psi is valid. Satisfiable has a short certificate (NP); valid generally does not (coNP).
  • Γ⊨ψ\Gamma \models \psi means Mod⁡(Γ)⊆Mod⁡(ψ)\operatorname{Mod}(\Gamma) \subseteq \operatorname{Mod}(\psi): no counterexamples. It is equivalent to Γ∪{¬ψ}\Gamma \cup \{\lnot\psi\} being unsatisfiable, and deduction moves a premise into the conclusion as antecedent: Γ∪{φ}⊨ψ\Gamma \cup \{\varphi\} \models \psi iff Γ⊨φ→ψ\Gamma \models \varphi \to \psi. Everything follows from inconsistent premises.
  • Every formula has equivalent CNF and DNF, but distribution can be exponential and for (x1∧y1)∨⋯∨(xn∧yn)(x_1 \land y_1) \lor \cdots \lor (x_n \land y_n) no equivalent CNF has fewer than 2n2^n clauses. Solvers use linear equisatisfiable Tseitin.