Exercises Notebook
Converted from
exercises.ipynbfor web reading.
Sets and Logic - Exercises
This notebook contains 10 progressive exercises for 02-Sets-and-Logic. Each exercise has a learner workspace followed by a complete reference solution. The goal is fluent foundational math for later linear algebra, calculus, probability, and ML sections.
Code cell 2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
try:
import seaborn as sns
sns.set_theme(style="whitegrid", palette="colorblind")
HAS_SNS = True
except ImportError:
plt.style.use("seaborn-v0_8-whitegrid")
HAS_SNS = False
mpl.rcParams.update({
"figure.figsize": (10, 6),
"figure.dpi": 120,
"font.size": 13,
"axes.titlesize": 15,
"axes.labelsize": 13,
"xtick.labelsize": 11,
"ytick.labelsize": 11,
"legend.fontsize": 11,
"legend.framealpha": 0.85,
"lines.linewidth": 2.0,
"axes.spines.top": False,
"axes.spines.right": False,
"savefig.bbox": "tight",
"savefig.dpi": 150,
})
np.random.seed(42)
print("Plot setup complete.")
Code cell 3
import numpy as np
import numpy.linalg as la
from decimal import Decimal, getcontext
from itertools import product
np.set_printoptions(precision=8, suppress=True)
np.random.seed(42)
def header(title):
print("\n" + "=" * len(title))
print(title)
print("=" * len(title))
def check_true(name, cond):
ok=bool(cond)
print(f"{'PASS' if ok else 'FAIL'} - {name}")
return ok
def check_close(name, got, expected, tol=1e-8):
ok=np.allclose(got, expected, atol=tol, rtol=tol)
print(f"{'PASS' if ok else 'FAIL'} - {name}")
if not ok:
print(' got =', got)
print(' expected=', expected)
return ok
def powerset(s):
items=list(s)
return [set(items[i] for i in range(len(items)) if mask & (1 << i)) for mask in range(1 << len(items))]
print("Chapter 01 helper setup complete.")
Exercise 1: Set Operations
Compute union, intersection, difference, and symmetric difference.
Code cell 5
# Your Solution
# Exercise 1 - learner workspace
# Write your solution here, then run the reference solution below to compare.
print("Learner workspace ready for Exercise 1.")
Code cell 6
# Solution
# Exercise 1 - Set Operations
header("Exercise 1: set operations")
A={1,2,3,5}; B={3,4,5,6}
print("union", A|B, "intersection", A&B)
check_true("intersection", A&B == {3,5})
check_true("symmetric difference", A^B == {1,2,4,6})
Exercise 2: De Morgan Laws
Verify over a finite universe.
Code cell 8
# Your Solution
# Exercise 2 - learner workspace
# Write your solution here, then run the reference solution below to compare.
print("Learner workspace ready for Exercise 2.")
Code cell 9
# Solution
# Exercise 2 - De Morgan Laws
header("Exercise 2: De Morgan")
U=set(range(8)); A={1,2,3}; B={3,4}
lhs=(U-A)&(U-B); rhs=U-(A|B)
print(lhs, rhs)
check_true("De Morgan", lhs==rhs)
Exercise 3: Truth Table
Build a truth table for .
Code cell 11
# Your Solution
# Exercise 3 - learner workspace
# Write your solution here, then run the reference solution below to compare.
print("Learner workspace ready for Exercise 3.")
Code cell 12
# Solution
# Exercise 3 - Truth Table
header("Exercise 3: truth table")
rows=[]
for p,q in product([False,True], repeat=2):
val=(not (p and q)) or p
rows.append(val); print(p,q,val)
check_true("tautology", all(rows))
Exercise 4: Quantifier Counterexample
Disprove for all x exists y: y < x over natural numbers with zero.
Code cell 14
# Your Solution
# Exercise 4 - learner workspace
# Write your solution here, then run the reference solution below to compare.
print("Learner workspace ready for Exercise 4.")
Code cell 15
# Solution
# Exercise 4 - Quantifier Counterexample
header("Exercise 4: quantifiers")
N=set(range(5))
truth={x:any(y<x for y in N) for x in N}
print(truth)
check_true("x=0 is counterexample", truth[0] is False)
Exercise 5: Indicator Vectors
Represent sets as binary indicator vectors.
Code cell 17
# Your Solution
# Exercise 5 - learner workspace
# Write your solution here, then run the reference solution below to compare.
print("Learner workspace ready for Exercise 5.")
Code cell 18
# Solution
# Exercise 5 - Indicator Vectors
header("Exercise 5: indicators")
U=list(range(6)); A={1,3,4}; B={3,5}
indA=np.array([u in A for u in U], dtype=int); indB=np.array([u in B for u in U], dtype=int)
check_close("intersection via product", indA*indB, np.array([u in A&B for u in U], dtype=int))
check_close("union via max", np.maximum(indA,indB), np.array([u in A|B for u in U], dtype=int))
Exercise 6: Boolean Masks
Use logical masks to filter examples by two predicates.
Code cell 20
# Your Solution
# Exercise 6 - learner workspace
# Write your solution here, then run the reference solution below to compare.
print("Learner workspace ready for Exercise 6.")
Code cell 21
# Solution
# Exercise 6 - Boolean Masks
header("Exercise 6: masks")
x=np.array([-2,-1,0,1,2,3])
mask=(x>0)&(x%2==1)
print("selected", x[mask])
check_close("positive odd", x[mask], np.array([1,3]))
Exercise 7: Jaccard Similarity
Compute .
Code cell 23
# Your Solution
# Exercise 7 - learner workspace
# Write your solution here, then run the reference solution below to compare.
print("Learner workspace ready for Exercise 7.")
Code cell 24
# Solution
# Exercise 7 - Jaccard Similarity
header("Exercise 7: Jaccard")
A=set('machine'); B=set('learning')
j=len(A&B)/len(A|B)
print("Jaccard", j)
check_true("range", 0<=j<=1)
check_close("manual", j, len(A&B)/len(A|B))
Exercise 8: Power Set Size
Generate a power set and confirm it has subsets.
Code cell 26
# Your Solution
# Exercise 8 - learner workspace
# Write your solution here, then run the reference solution below to compare.
print("Learner workspace ready for Exercise 8.")
Code cell 27
# Solution
# Exercise 8 - Power Set Size
header("Exercise 8: power set")
S={'a','b','c','d'}
P=powerset(S)
print("count", len(P))
check_true("2^n subsets", len(P)==2**len(S))
Exercise 9: Predicate Logic for Data Quality
Combine predicates for a tiny data-quality filter.
Code cell 29
# Your Solution
# Exercise 9 - learner workspace
# Write your solution here, then run the reference solution below to compare.
print("Learner workspace ready for Exercise 9.")
Code cell 30
# Solution
# Exercise 9 - Predicate Logic for Data Quality
header("Exercise 9: data predicates")
length=np.array([5,20,200,50]); toxic=np.array([False,False,True,False]); duplicate=np.array([False,True,False,False])
keep=(length>=10)&(length<=100)&(~toxic)&(~duplicate)
print("keep", keep)
check_close("only item 4 kept", keep, np.array([False,False,False,True]))
Exercise 10: Implication as Constraint
Convert if flagged then reviewed into a Boolean check.
Code cell 32
# Your Solution
# Exercise 10 - learner workspace
# Write your solution here, then run the reference solution below to compare.
print("Learner workspace ready for Exercise 10.")
Code cell 33
# Solution
# Exercise 10 - Implication as Constraint
header("Exercise 10: implication constraint")
flagged=np.array([True,True,False,False]); reviewed=np.array([True,False,False,True])
valid=(~flagged)|reviewed
print("valid rows", valid)
check_close("one violation", valid, np.array([True,False,True,True]))