Ran Wei/CS Series/04
中文
Computer Science Fundamentals — Ran Wei

Module 04: Mathematical foundations

Use logic, sets, relations, proof and probability to state what a program means and justify its claims.

≈ 5 hours4 sessions2 labs8 exercises6 quiz questions

By the end you can

  • Build truth tables.
  • Use sets and relations.
  • Distinguish functions and injectivity.
  • Construct induction proofs.
  • Compute finite conditional probabilities.

Before you start

Recommended modules: 01, 03.

Know functions and loops. No previous proof course is assumed. ∀ means for every; ∃ means there exists.

Contents

Study plan

5 hours

Four 75-minute sessions including practice. Allow longer for extensions or unfamiliar prerequisites. Progress is saved locally and shared between language editions.

Session 175 min
Concepts and worked examples
Session 375 min
Apply and extend
1

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.

Check your understanding

When is p→q false?

Worked solution

Only when p is true and q is false.

2

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.

Check your understanding

If A={1,2}, B={2,3}, what is A−B?

Worked solution

{1}; it is not the same as B−A={3}.

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.

Check your understanding

Can 5 distinct keys occupy 4 buckets without collision?

Worked solution

No, by the pigeonhole principle.

4

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.

Check your understanding

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.

5

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.

Check your understanding

Are disjoint events with positive probabilities independent?

Worked solution

No: their joint probability is zero but the product is positive.

6

Common misconceptions

  • The converse of an implication is not its contrapositive.
  • Equally likely outcomes are an assumption, not automatic.
7

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.

8

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.

Download m04_logic.py

"""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))
Captured output
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]
  1. Replace the contrapositive with q→p and find a counterexample.
  2. 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.

9

Lab 2 — Exact probability and induction checks

Two labelled dice have 36 equally likely ordered outcomes. Fractions avoids float approximation.

Download m04_probability.py

"""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)
Captured output
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
  1. Compute P(sum=8) and P(sum=8 | first=1).
  2. 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.

10

Exercises with worked solutions

Try before opening the solution. ★ applies an idea; ★★ combines ideas; ★★★ asks for design or proof.

Exercise 1 — Negate a claim★

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.

Exercise 2 — Set calculation★

Compute union and intersection of {1,3} and {3,5}.

Worked solution

Union {1,3,5}; intersection {3}.

Exercise 3 — Converse★★

Does p→q imply q→p? Give a counterexample.

Worked solution

No. p=False, q=True satisfies p→q but violates q→p.

Exercise 4 — Injectivity★★

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.

Exercise 5 — Conditional chance★★

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.

Exercise 6 — Induction★★★

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.

Exercise 7 — Expectation★★

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.

Exercise 8 — Relations★★★

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.

11

Self-check quiz

Choose an answer for feedback; reset to retry. A text answer key is available without JavaScript.

1

A universal claim is disproved by?

2

A∩B means?

3

Induction needs?

4

A function assigns each input?

5

P(A|B) requires?

6

A fair die's expected value?

Answer key
  1. A — Universal means every valid case.
  2. B — Intersection retains shared membership.
  3. C — The step extends the result beyond checked instances.
  4. A — Its domain elements must each be mapped.
  5. B — We divide by P(B).
  6. C — The mean is (1+…+6)/6.
12

Guided reading

13

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.

14

Key terms

TermMeaning
InvariantA property preserved at specified execution points.
Conditional probabilityProbability restricted to a condition with positive probability.
BijectionA function both injective and surjective.