Python Introduction to artificial intelligence: 13 practice problems
UNIT 4 of the free Python for AI course. Read the short theory, then solve the problems below with instant tests. Python runs in your browser.
▶ Practise Introduction to artificial intelligence nowAll topicsTheory: Introduction to artificial intelligence in Python
THEORY
------
* AI = building machines that perform tasks needing human-like intelligence: reasoning,
learning, perception, language, planning, decision making.
History: Turing Test (Alan Turing, 1950) · "AI" coined by John McCarthy, Dartmouth 1956 ·
expert systems (1970s-80s) · Deep Blue beats Kasparov (1997) · deep learning boom (2012, ImageNet) ·
AlphaGo (2016) · Transformers (2017) · ChatGPT / LLMs (2022+).
* AI ⊃ MACHINE LEARNING (learn patterns from data instead of hand-written rules)
⊃ DEEP LEARNING (multi-layer neural networks).
* TYPES BY CAPABILITY: Narrow/Weak AI (one task — ALL current AI), General AI (AGI, human-level,
not achieved), Super AI (hypothetical).
TYPES BY FUNCTIONALITY: Reactive machines (Deep Blue) · Limited memory (self-driving cars) ·
Theory of mind · Self-aware (last two are research/hypothetical).
* APPROACHES: SYMBOLIC / RULE-BASED (if-then rules written by experts, e.g. expert systems)
vs DATA-DRIVEN (machine learning).
* ML TYPES
Supervised labelled examples (input -> correct output). Classification (spam / not spam)
and Regression (predict a number: house price).
Unsupervised no labels; find structure. Clustering (customer segments), dimensionality reduction.
Reinforcement an AGENT acts in an ENVIRONMENT and learns from REWARDS (games, robots).
* INTELLIGENT AGENT: perceives through SENSORS, acts through ACTUATORS. PEAS = Performance measure,
Environment, Actuators, Sensors. Simple REFLEX agent: action = rule(current percept).
* SEARCH: problem solving as finding a path in a graph. BFS (shortest path in steps, uses a QUEUE),
DFS (uses a stack), A* (uses a heuristic).
* ML WORKFLOW: collect data -> clean -> features -> split TRAIN / TEST -> train model -> evaluate on
TEST data (never seen) -> tune -> deploy.
* EVALUATION (classification), with TP, FP, FN, TN from the CONFUSION MATRIX:
accuracy = (TP + TN) / total precision = TP / (TP + FP) "of predicted positives, how many right"
recall = TP / (TP + FN) "of real positives, how many found" F1 = 2PR / (P + R)
Accuracy misleads on imbalanced data (99% "not fraud" model is useless).
* SIMPLE MODELS: k-Nearest Neighbours (vote among the k closest training points),
Linear Regression (best straight line, least squares: slope = cov(x,y)/var(x)).
* OVERFITTING (memorises training data) vs UNDERFITTING (too simple). BASELINE = always predict
the most common class — your model must beat it.
* ETHICS: bias, fairness, privacy, transparency/explainability, accountability, job impact.
13 Introduction to artificial intelligence practice problems
1. Supervised, Unsupervised or Reinforcement? — return a list of answers
Easy1 way to solve📤 OUTPUT: return a list, e.g. ['supervised', 'unsupervised', 'reinforcement'…. Use `return`, not print().
("supervised" / "unsupervised" / "reinforcement") for:
1. Predict house prices from past sales with known prices
2. Group customers into segments without any labels
3. A robot learns to walk by getting rewards for moving forward
4. Classify emails as spam using 10,000 labelled emails
5. A program learns to play chess by playing itself and winning/losing
6. Find unusual patterns in network traffic with no labelled attacks
Solve “Supervised, Unsupervised or Reinforcement? — return a list of answers” in your browser →2. Simple Reflex Agent — the classic 2-room vacuum world
Easy2 ways to solve📤 OUTPUT: return a str (text), e.g. 'Suck'. Use `return`, not print().
Percept = (location "A" or "B", is_dirty). Rules: dirty -> "Suck"; in A -> "Right"; in B -> "Left".
vacuum_agent("A", True) -> "Suck" vacuum_agent("B", False) -> "Left"
Solve “Simple Reflex Agent — the classic 2-room vacuum world” in your browser →3. Rule-Based Expert System — smart AC
Easy1 way to solve📤 OUTPUT: return a str (text), e.g. 'cool'. Use `return`, not print().
Rules, checked in order: temp < 18 -> "heat"; temp > 28 -> "cool";
humidity > 70 -> "dehumidify"; otherwise "idle".
thermostat_expert(30, 80) -> "cool"
Solve “Rule-Based Expert System — smart AC” in your browser →4. Train / Test Split (no shuffling)
Easy1 way to solve📤 OUTPUT: return a tuple, e.g. ([1, 2, 3], [4, 5]). Use `return`, not print().
n_test = int(len(data) * test_ratio); the LAST n_test items are the test set.
Return (train, test).
train_test_split([1, 2, 3, 4, 5], 0.4) -> ([1, 2, 3], [4, 5])
Solve “Train / Test Split (no shuffling)” in your browser →5. Confusion Matrix Counts (positive class = 1)
Easy2 ways to solve📤 OUTPUT: return a tuple, e.g. (2, 1, 1, 1). Use `return`, not print().
Return (TP, FP, FN, TN).
confusion_counts([1, 0, 1, 1, 0], [1, 1, 0, 1, 0]) -> (2, 1, 1, 1)
Solve “Confusion Matrix Counts (positive class = 1)” in your browser →6. Disease Test Evaluation — precision, recall, F1 (rounded to 2)
Medium1 way to solve📤 OUTPUT: return a tuple, e.g. (0.67, 0.67, 0.67). Use `return`, not print().
Real world: A COVID test — recall matters (don't miss sick people).
Return (precision, recall, f1); any 0/0 -> 0.0.
precision_recall_f1([1, 0, 1, 1, 0], [1, 1, 0, 1, 0]) -> (0.67, 0.67, 0.67)
Solve “Disease Test Evaluation — precision, recall, F1 (rounded to 2)” in your browser →7. k-Nearest Neighbours — classify a new fruit
Medium2 ways to solve📤 OUTPUT: return a str (text), e.g. 'apple'. Use `return`, not print().
points: list of (x, y) features, labels: list of class names. Find the k training points closest
to query (Euclidean distance) and return the most common label among them (tests avoid ties).
points = [(1, 1), (1, 2), (5, 5), (6, 5)], labels = ["apple", "apple", "orange", "orange"]
knn_predict(points, labels, (2, 1), 3) -> "apple"
Solve “k-Nearest Neighbours — classify a new fruit” in your browser →8. Linear Regression from Scratch — least squares
Medium2 ways to solve📤 OUTPUT: return a tuple, e.g. (2.0, 1.0). Use `return`, not print().
Real world: Predict salary from years of experience.
slope = sum((x - mx)(y - my)) / sum((x - mx)^2); intercept = my - slope * mx. Round both to 2.
fit_line([1, 2, 3, 4], [3, 5, 7, 9]) -> (2.0, 1.0)
Solve “Linear Regression from Scratch — least squares” in your browser →9. Majority-Class Baseline
Easy2 ways to solve📤 OUTPUT: return a float, e.g. 0.75. Use `return`, not print().
Accuracy of always predicting the most common label, rounded to 2.
baseline_accuracy(["ok", "ok", "fraud", "ok"]) -> 0.75
Solve “Majority-Class Baseline” in your browser →10. Route Finding with Breadth-First Search — AI search
Medium2 ways to solve📤 OUTPUT: return a list, e.g. ['A', 'B', 'D', 'F']. Use `return`, not print().
Real world: Fewest metro stops between two stations.
graph: dict {node: [neighbours]}. Return the shortest path as a list of nodes (neighbours explored in
the given order), or [] if unreachable.
g = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": ["F"], "E": ["F"], "F": []}
bfs_path(g, "A", "F") -> ["A", "B", "D", "F"]
Hint: queue of paths (collections.deque), a `visited` set.
Solve “Route Finding with Breadth-First Search — AI search” in your browser →11. Game AI Building Block — detect the winner
Medium2 ways to solve📤 OUTPUT: return a str (text), e.g. 'X'. Use `return`, not print().
board: list of 3 strings like ["XOX", "OXO", " X"]. Return "X", "O", or "" if nobody has 3 in a
row (rows, columns, diagonals).
tic_tac_toe_winner(["XOX", "OXO", " X"]) -> "X"
Solve “Game AI Building Block — detect the winner” in your browser →12. Email Spam Filter with Naive Bayes — interview at an email company (ML team)
Project1 way to solve📤 OUTPUT: return a list, e.g. ['spam', 'ham', 'spam', 'ham']. Use `return`, not print(). Interviewer: "No libraries. Implement multinomial Naive Bayes from scratch." tokens: lower-case words split on whitespace, with . , ! ? stripped P(label) from label counts; P(word | label) = (count + 1) / (total words in label + vocabulary size) score(label) = log P(label) + sum of log P(word | label) for test words SEEN in training Return the predicted label for each test doc (ties -> "ham").Solve “Email Spam Filter with Naive Bayes — interview at an email company (ML team)” in your browser →
13. Stage 18 — "Did you mean ...?" (AI as SEARCH: edit distance with dynamic programming)
Compiler1 way to solve📤 OUTPUT: return a str (text) (or None in the special case), e.g. 'print'. Use `return`, not print().
Implement Levenshtein distance (insert / delete / substitute = 1 each) yourself.
Return the known name with the smallest distance to `name` if that distance <= 2
(ties -> alphabetically first), else None.
suggest_name("pirnt", ["print", "let", "total"]) -> "print"
Solve “Stage 18 — "Did you mean ...?" (AI as SEARCH: edit distance with dynamic programming)” in your browser →← DATA VISUALIZATION: Matplotlib & Seaborn BASICS OF NEURAL NETWORKS (with PREREQUISITE: derivatives & gradients) →