notebook-exercises
Skill2 starsChanged 35 days agoMITView on GitHub
Add self-checking exercises after each topic in Jupyter lesson notebooks. Each question gets a stub cell and a check() cell that compares the answer against a stored hash, so solutions never appear in the notebook. Use when asked to "add exercises", "make practice questions", or "add self-check questions" to a .ipynb.
The file
We split this skill into the rules it gives an agent
6 rules. About 0 are common, 2 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 8
Add a short Exercise section after each topic of a lesson notebook.
- Very specific: line 14
Never change lesson cells: Only insert new cells. Tag every inserted cell with "tags": ["exercise"] in its metadata so they can be found or …
- Very specific: line 16
Write questions in the same language and tone as the notebook.
- Very specific: line 31
Add a <details><summary>Hint</summary> … </details> block to questions that are not obvious.
- Distinctive: line 122
After each topic, one exercise block:
- Distinctive: line 181
Delete the temporary copies afterwards.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Notebook self-check exercises
Add a short Exercise section after each topic of a lesson notebook. Students
replace None with code, run a check(...) cell, and get ✅ or an
AssertionError. Answers are stored only as truncated SHA-256 hashes.
Rules
- Never change lesson cells. Only insert new cells. Tag every inserted cell
with
"tags": ["exercise"]in its metadata so they can be found or stripped later. - Write questions in the same language and tone as the notebook. Keep them short:
2–4 questions per topic, numbered
q1, q2, …across the whole notebook. - Each answer must be a deterministic value: a number, string, bool, list,
tuple, dict, set,
SeriesorDataFrame. Fixrandom_state/seeds whenever the answer depends on randomness. Avoid answers that depend on wall-clock time, file paths, or library-version-specific output formatting. - Notebooks that run on data in the repo (pandas, data prep, classic ML):
questions may use the lesson's own variables (e.g.
df,X_train,model). Compute the answers by actually executing the notebook. - Notebooks needing GPUs, API keys, or big model downloads (deep learning, LLM/LangChain, OCR): make every exercise self-contained — small tensors, toy arrays, fake/stub LLM classes, hard-coded strings — so it runs on a laptop CPU without network access. Test the concept the lesson taught, not the model output.
- Skip notebooks that are activity templates or that cannot run at all; say which ones were skipped and why.
- Add a
<details><summary>Hint</summary> … </details>block to questions that are not obvious.
Cell layout
Insert near the top (after the lesson's import cell):
- Markdown — how the exercises work:
## ✏️ About the exercises in this notebook
After each topic there is a short **Exercise** section.
1. Run the checker cell below once. Run it after the imports and before any exercise.
2. For each question, replace `None` with your code, then run the `check(...)` cell under it.
3. A ✅ means you are correct. An `AssertionError` tells you what is still wrong.
The exercises use the variables the lesson has created by that point, so **run the lesson cells above an exercise first**.
Answers are stored as hashes, so they don't appear in this notebook. Floats are compared after rounding to 4 decimals.- Code — the checker (copy verbatim; only
_ANSWERSchanges per notebook):
# ===== Answer checker: run this cell first (do not edit) =====
import hashlib
import numpy as np
import pandas as pd
def _norm(x):
if x is None or x is pd.NA or x is pd.NaT:
return 'nan'
if isinstance(x, pd.DataFrame):
return _norm({c: x[c].to_dict() for c in x.columns})
if isinstance(x, pd.Series):
return _norm(x.to_dict())
if isinstance(x, (pd.Index, np.ndarray)):
return _norm(x.tolist())
if isinstance(x, dict):
return '{' + ','.join(sorted(f'{_norm(k)}:{_norm(v)}' for k, v in x.items())) + '}'
if isinstance(x, (set, frozenset)):
return '{' + ','.join(sorted(_norm(v) for v in x)) + '}'
if isinstance(x, (list, tuple)):
return '[' + ','.join(_norm(v) for v in x) + ']'
if isinstance(x, (bool, np.bool_)):
return str(bool(x))
if isinstance(x, (int, np.integer)):
return str(int(x))
if isinstance(x, (float, np.floating)):
x = float(x)
if np.isnan(x):
return 'nan'
r = round(x, 4)
return str(int(r)) if r.is_integer() else f'{r:.4f}'
if isinstance(x, pd.Timestamp):
return x.isoformat()
return str(x).strip()
_KINDS = {
int: ((int, np.integer), 'an integer'),
float: ((int, float, np.integer, np.floating), 'a number'),
str: ((str,), 'a string'),
list: ((list,), 'a list'),
tuple: ((tuple,), 'a tuple'),
pd.Series: ((pd.Series,), 'a pandas Series'),
pd.DataFrame: ((pd.DataFrame,), 'a pandas DataFrame'),
}
def check(qid, value, kind=None, columns=None, transform=None):
"""Assert that `value` is the correct answer for question `qid`.
Floats are compared after rounding to 4 decimal places."""
assert value is not None, f'{qid}: no answer yet - replace None with your code'
if kind is not None:
types, name = _KINDS.get(kind, ((kind,), kind.__name__))
assert isinstance(value, types), f'{qid}: expected {name}, got {type(value).__name__}'
if columns is not None:
assert list(value.columns) == list(columns), f'{qid}: expected columns {list(columns)}, got {list(value.columns)}'
if transform is not None:
value = transform(value)
digest = hashlib.sha256(_norm(value).encode()).hexdigest()[:16]
assert digest == _ANSWERS[qid], f'{qid}: not correct yet - try again (open the hint if you are stuck)'
print(f'✅ {qid} correct!')
_ANSWERS = {
"q1": "<hash>",
"q2": "<hash>",
}For self-contained notebooks that don't otherwise import pandas, keep the checker as is (pandas/numpy are assumed installed).
- After each topic, one exercise block:
### ✏️ Exercise: <topic name>then per question, three cells:
**Q1.** What is the **median** `Price`?
<details><summary>Hint</summary>
Use `.median()` on the column.
</details># YOUR CODE HERE
q1 = Nonecheck('q1', q1, float)check options:
kind:int,float,str,list,tuple,pd.Series,pd.DataFrame, or any type.columns=[...]: require exact DataFrame columns in order.transform=fn: normalise before hashing when many forms are correct, e.g.transform=sortedfor "any order",transform=lambda s: s.lower()for case,transform=lambda df: df.reset_index(drop=True)when the index doesn't matter. The same transform must be applied when computing the stored hash.
Workflow
- Read the notebook and list its topics (usually its
##headings). Decide whether it can run as-is or needs self-contained exercises. - Draft questions with solutions in a scratch file (not the notebook):
qid, question text, hint, solution code,kind, optionaltransform, and the index of the lesson cell after which the block goes. - Compute the answers by execution. Build a temporary copy of the notebook
with the checker cell and the solution code in each stub, then execute it
(
jupyter nbconvert --to notebook --execute --ExecutePreprocessor.timeout=600ornbclient). In the solution copy, temporarily make the hash available by adding, right after each solution, a cell like:
Collect the printed hashes intoprint('HASH', 'q1', hashlib.sha256(_norm(TRANSFORM(q1)).encode()).hexdigest()[:16])_ANSWERS. Never hand-compute a hash. - Write the real notebook with Python +
json(ornbformat): insert the intro, checker (with real_ANSWERS) and exercise cells, all taggedexercise, with stubs set toqN = None. Do not touch existing cells, outputs, or metadata. Clear outputs of the inserted cells. - Verify both ways:
- Solution copy: every
checkprints ✅. - Student copy (stubs =
None): the checker cell runs, and eachcheckraisesAssertionError: qN: no answer yet— nothing else errors. Delete the temporary copies afterwards.
- Solution copy: every
- Report per notebook: number of questions, which were self-contained,
anything skipped. Then confirm with
git diff --statthat only the intended notebooks changed.
Removing exercises later
import json, sys
p = sys.argv[1]
nb = json.load(open(p))
nb['cells'] = [c for c in nb['cells'] if 'exercise' not in c.get('metadata', {}).get('tags', [])]
json.dump(nb, open(p, 'w'), indent=1, ensure_ascii=False)Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

