Logic and quantifiers
A proposition is a statement with a truth value. Negation flips it; conjunction requires both inputs; disjunction requires at least one. Implication p→q means not p or q: it is false only when p is true and q is false. This models a promise: when the precondition holds, the postcondition must hold. It is not a claim that p causes q. Quantifiers extend statements: every record has an ID differs from some record has an ID. Negating ∀x P(x) gives ∃x not P(x); one counterexample defeats a universal claim.
When is p→q false?
Worked solution
Only when p is true and q is false.
Sets and relations
A set contains distinct elements without positional order. Union collects elements in either set; intersection keeps elements in both; difference A−B keeps elements only in A. A relation is a set of ordered pairs: borrowed_by can relate a book ID to a member ID. Reflexive means each element relates to itself; symmetric means each related pair reverses; transitive means xRy and yRz imply xRz. Equality has all three properties. A directed dependency relation need not be symmetric.
If A={1,2}, B={2,3}, what is A−B?
Worked solution
{1}; it is not the same as B−A={3}.
Functions and counting
A function maps each domain element to exactly one codomain element. Injective means distinct inputs have distinct outputs; surjective means every codomain element is reached; bijective means both. If an ID-to-record function is injective, no two IDs map to the same record under that model. A pair of independent choices with a and b possibilities has a×b combinations. This counts configurations, not probabilities unless outcomes are equally likely. Mapping more than k objects into k buckets forces at least one shared bucket: the pigeonhole principle explains why hash collisions cannot always be avoided.
Can 5 distinct keys occupy 4 buckets without collision?
Worked solution
No, by the pigeonhole principle.
Proof and induction
A direct proof starts from assumptions and derives the claim. A counterexample disproves a universal statement. Induction proves a statement indexed by nonnegative integers: establish a base case, then prove that assuming it at k implies it at k+1. For 1+…+n=n(n+1)/2, n=0 gives zero. Add k+1 to k(k+1)/2 to obtain (k+1)(k+2)/2. Checking ten values is useful debugging but does not replace that step for infinitely many n. Loop invariants use a related initialisation-and-preservation structure.
What must follow a base case in an induction proof?
Worked solution
An implication from the claim at k to the claim at k+1.
Probability and expectation
A finite sample space lists outcomes. For equally likely outcomes, P(A)=|A|/|Ω|. Conditional probability restricts attention to B: P(A|B)=P(A∩B)/P(B), requiring P(B)>0. Independence means P(A∩B)=P(A)P(B); it is not the same as disjointness. Expected value weights values by probabilities. A fair die has expected value 3.5 even though no roll is 3.5. Linearity gives E[X+Y]=E[X]+E[Y] without requiring independence; other identities, such as multiplying expectations, do require additional assumptions.
Are disjoint events with positive probabilities independent?
Worked solution
No: their joint probability is zero but the product is positive.
Common misconceptions
- The converse of an implication is not its contrapositive.
- Equally likely outcomes are an assumption, not automatic.
Lab setup
Download each script and run it in a terminal with Python 3.11 or later: python m04_logic.py. On Windows, py -3 is an alternative; on some systems use python3. The labs use only the standard library. Predict the result before running, then complete the variations. Run without -O so assertions remain enabled. Outputs below were captured by the builder. Code and output are identical in both language editions.
Lab 1 — Truth tables and sets
Enumerate all four Boolean input pairs. The code checks implication against its contrapositive and verifies De Morgan's law.
"""Enumerate finite cases to check logical equivalence and set operations."""
from itertools import product
for p, q in product([False, True], repeat=2):
implication = (not p) or q
contrapositive = q or (not p) # (not q) implies (not p)
assert implication == contrapositive
assert (not (p and q)) == ((not p) or (not q))
print(int(p), int(q), "implies:", int(implication))
available = {1, 2, 3}
requested = {2, 3, 4}
print("intersection:", sorted(available & requested))
print("union:", sorted(available | requested))
print("missing:", sorted(requested - available))
0 0 implies: 1
0 1 implies: 1
1 0 implies: 0
1 1 implies: 1
intersection: [2, 3]
union: [1, 2, 3, 4]
missing: [4]
- Replace the contrapositive with q→p and find a counterexample.
- Add symmetric difference for the sets.
Worked solution
p=False, q=True makes p→q true but q→p false. Symmetric difference is {1,4}; it retains membership in exactly one set.
Lab 2 — Exact probability and induction checks
Two labelled dice have 36 equally likely ordered outcomes. Fractions avoids float approximation.
"""Exact finite probability, conditional probability and a summation identity."""
from fractions import Fraction
outcomes = [(a, b) for a in range(1, 7) for b in range(1, 7)]
event = [(a, b) for a, b in outcomes if a + b == 7]
condition = [(a, b) for a, b in outcomes if a == 1]
joint = [x for x in condition if sum(x) == 7]
print("P(sum=7):", Fraction(len(event), len(outcomes)))
print("P(sum=7 | first=1):", Fraction(len(joint), len(condition)))
for n in [0, 1, 5, 10]:
total = sum(range(1, n + 1))
assert total == n * (n + 1) // 2
print("n:", n, "sum:", total)
P(sum=7): 1/6
P(sum=7 | first=1): 1/6
n: 0 sum: 0
n: 1 sum: 1
n: 5 sum: 15
n: 10 sum: 55
- Compute P(sum=8) and P(sum=8 | first=1).
- Change the summation endpoint to exclude n; find a failing case.
Worked solution
Five pairs total eight, giving 5/36. With the first die one, eight is impossible: zero. Excluding n breaks the formula already at n=1, because the computed sum becomes zero.
Exercises with worked solutions
Try before opening the solution. ★ applies an idea; ★★ combines ideas; ★★★ asks for design or proof.
Negate: every book has a unique ID.
Worked solution
There exists a book that does not have a unique ID. Specify whether missing IDs count as invalid in the domain.
Compute union and intersection of {1,3} and {3,5}.
Worked solution
Union {1,3,5}; intersection {3}.
Does p→q imply q→p? Give a counterexample.
Worked solution
No. p=False, q=True satisfies p→q but violates q→p.
Is f(x)=x² injective on integers? On nonnegative integers?
Worked solution
Not on integers: −2 and 2 both give 4. It is injective on nonnegative integers because larger nonnegative inputs have larger squares.
For a fair die, compute P(even | greater than 3).
Worked solution
The restricted outcomes are 4,5,6; two are even. Probability 2/3.
Prove 0+…+n=n(n+1)/2.
Worked solution
Base n=0: both sides zero. Assume at k. Adding k+1 gives k(k+1)/2+(k+1)=(k+1)(k+2)/2, the claim for k+1.
Find the expected number of heads in two fair coin flips.
Worked solution
Each indicator has expectation 1/2. Add them to get 1; alternatively weight counts 0,1,2 by 1/4,1/2,1/4.
Is 'has the same author as' an equivalence relation if every book has exactly one author?
Worked solution
Yes: each book shares its author with itself; equality reverses; equal authors chain transitively. Missing or multiple authors require a revised relation.
Self-check quiz
Choose an answer for feedback; reset to retry. A text answer key is available without JavaScript.
A universal claim is disproved by?
A∩B means?
Induction needs?
A function assigns each input?
P(A|B) requires?
A fair die's expected value?
Answer key
- A — Universal means every valid case.
- B — Intersection retains shared membership.
- C — The step extends the result beyond checked instances.
- A — Its domain elements must each be mapped.
- B — We divide by P(B).
- C — The mean is (1+…+6)/6.
Guided reading
- MIT Mathematics for Computer Science — Read the opening proof and induction chapters; identify assumptions in one proof.
Review and the next step
Explain why tests and proofs provide different evidence. Write one invariant for catalogue counting. Module 05 uses these tools to analyse search and sorting.
Key terms
| Term | Meaning |
|---|---|
| Invariant | A property preserved at specified execution points. |
| Conditional probability | Probability restricted to a condition with positive probability. |
| Bijection | A function both injective and surjective. |