{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Week 01 — Python basics & data structures (Syllabus 01)\n", "\n", "**Capstone track**: **B — Data collector + LLM analysis (OpenRouter) → report**\n", "\n", "### What you’ll build this week\n", "By the end of Week 01 you will have:\n", "\n", "- A clear **capstone dataset goal** (what data, why it matters, what you’ll do with it)\n", "- A stable **item schema** (what a “record” looks like)\n", "- Solid fundamentals in **syntax, control flow, functions, core data structures, mutability**, and **comprehensions / generators / decorators**\n", "\n", "### Primary resources\n", "- **CS50P** (use as the main course): [CS50P](https://cs50.harvard.edu/python/)\n", "- **Python docs** (source of truth): [Python 3 docs](https://docs.python.org/3/)\n", "\n", "---\n", "\n", "## Lesson 01.1 — Introduction, control structures, functions\n", "\n", "### Learn\n", "- CS50P: Weeks **0–2** (Functions/Variables, Conditionals, Loops)\n", "- Python docs: control flow, functions, truthiness\n", "\n", "### You must understand\n", "- Variables, types, truthiness\n", "- `if/elif/else`, `for`, `while`, `break/continue`\n", "- Defining functions, parameters, return values\n", "- The idea of **pure functions** vs side effects (print, file write, network)\n", "\n", "### Lesson assignment (deliverables)\n", "- **A1 (skills)**: Write 10 short functions (each 5–15 lines) that:\n", " - validate input\n", " - transform data\n", " - return results (no prints inside core logic)\n", "- **A2 (capstone)**: Write a short design note (in your own words):\n", " - what data you’ll collect (API or websites)\n", " - what questions you’ll answer with the data\n", " - what the final output will look like (report/dashboard)\n", "\n", "---\n", "\n", "## Lesson 01.2 — Lists, tuples, dictionaries, sets (immutability & mutability)\n", "\n", "### Learn\n", "- Python docs: list/tuple/dict/set; copying vs aliasing\n", "\n", "### You must understand\n", "- List vs tuple (mutability, hashability)\n", "- Dict basics: keys/values, `.get()`, `.items()`\n", "- Set basics: membership, union/intersection\n", "- **Aliasing** vs **copying** (shallow copy vs deep copy)\n", "\n", "### Lesson assignment (deliverables)\n", "- **A3 (skills)**: Create a notebook section called “Mutability proofs” with 6 examples:\n", " - at least 2 examples that surprise beginners (aliasing + nested lists)\n", "- **A4 (capstone)**: Define your **Item schema** (one record):\n", " - required fields (id, source, url, title, text/summary, fetched_at, raw_path…)\n", " - optional fields\n", " - define what makes an item “the same” (unique key)\n", "\n", "---\n", "\n", "## Lesson 01.3 — List comprehensions, generators, decorators\n", "\n", "### Learn\n", "- Python docs: iteration protocol, generator functions (`yield`), `functools`\n", "\n", "### You must understand\n", "- When to use list comprehension vs generator expression\n", "- How `yield` enables streaming pipelines\n", "- What decorators do (wrap functions) and why they’re useful\n", "\n", "### Lesson assignment (deliverables)\n", "- **A5 (skills)**: Implement:\n", " - one list comprehension with filtering + transformation\n", " - one generator that streams lines from text\n", "- **A6 (capstone)**: Implement **two decorators** you will reuse later:\n", " - `@retry` (handles transient failures)\n", " - `@timeit` (measures runtime)\n", "\n", "---\n", "\n", "## Week 01 capstone milestone (Track B)\n", "\n", "### Goal\n", "End Week 01 with a *tight* foundation and a clear capstone direction.\n", "\n", "### Deliverables\n", "- **D1**: `Item` schema (as a dataclass) + small sample items (5–10 examples)\n", "- **D2**: `@retry` + `@timeit` decorators (with tests via simple `assert`s)\n", "- **D3**: A written dataset goal + 2 candidate sources (APIs or sites)\n", "\n", "---\n", "\n", "## Optional add-on (DSA/LeetCode)\n", "- 6 problems: **arrays/strings** (2 easy, 3 medium, 1 review)\n", "- Write down: pattern + invariant + complexity for each\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from __future__ import annotations\n", "\n", "from dataclasses import dataclass\n", "from datetime import datetime, timezone\n", "from functools import wraps\n", "from typing import Callable, Iterable, Iterator, TypeVar\n", "\n", "T = TypeVar(\"T\")\n", "\n", "\n", "def timeit(fn: Callable[..., T]) -> Callable[..., T]:\n", " \"\"\"Measure runtime of a function call (prints duration).\"\"\"\n", "\n", " @wraps(fn)\n", " def wrapper(*args, **kwargs):\n", " import time\n", "\n", " t0 = time.perf_counter()\n", " out = fn(*args, **kwargs)\n", " dt = time.perf_counter() - t0\n", " print(f\"{fn.__name__} took {dt:.6f}s\")\n", " return out\n", "\n", " return wrapper\n", "\n", "\n", "def retry(retries: int = 3, exceptions: tuple[type[BaseException], ...] = (Exception,)):\n", " \"\"\"Retry decorator for transient failures.\n", "\n", " TODO:\n", " - Add optional backoff (sleep) strategy\n", " - Only retry specific exception types\n", " \"\"\"\n", "\n", " def deco(fn):\n", " @wraps(fn)\n", " def wrapper(*args, **kwargs):\n", " last_err = None\n", " for _ in range(retries + 1):\n", " try:\n", " return fn(*args, **kwargs)\n", " except exceptions as e:\n", " last_err = e\n", " assert last_err is not None\n", " raise last_err\n", "\n", " return wrapper\n", "\n", " return deco\n", "\n", "\n", "def chunked(xs: Iterable[T], size: int) -> Iterator[list[T]]:\n", " \"\"\"Yield lists of length up to `size` from an iterable.\"\"\"\n", " if size <= 0:\n", " raise ValueError(\"size must be > 0\")\n", "\n", " buf: list[T] = []\n", " for x in xs:\n", " buf.append(x)\n", " if len(buf) == size:\n", " yield buf\n", " buf = []\n", " if buf:\n", " yield buf\n", "\n", "\n", "@dataclass(frozen=True)\n", "class Item:\n", " \"\"\"One normalized record in your capstone dataset.\"\"\"\n", "\n", " id: str\n", " source: str\n", " url: str\n", " title: str\n", " text: str\n", " fetched_at: str # ISO-8601\n", "\n", "\n", "def now_iso() -> str:\n", " return datetime.now(timezone.utc).isoformat()\n", "\n", "\n", "# === Exercises (edit and rerun) ===\n", "\n", "@timeit\n", "def demo() -> int:\n", " return sum(x * x for x in range(10_000))\n", "\n", "\n", "demo()\n", "\n", "assert list(chunked([1, 2, 3, 4, 5], 2)) == [[1, 2], [3, 4], [5]]\n", "\n", "sample = Item(\n", " id=\"example-1\",\n", " source=\"demo\",\n", " url=\"https://example.com\",\n", " title=\"Example\",\n", " text=\"Hello world\",\n", " fetched_at=now_iso(),\n", ")\n", "assert sample.id == \"example-1\"\n", "print(sample)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\"\"\"Capstone B — Week 01 scaffold\n", "\n", "This cell is intentionally *minimal* and stdlib-only.\n", "You’ll expand it in Weeks 02–05 (HTTP, scraping, DB, OpenRouter).\n", "\"\"\"\n", "\n", "from dataclasses import asdict\n", "import json\n", "from pathlib import Path\n", "\n", "DATA_DIR = Path(\"data\")\n", "DATA_DIR.mkdir(exist_ok=True)\n", "\n", "SAMPLES_PATH = DATA_DIR / \"items.sample.jsonl\"\n", "\n", "# TODO (A4): finalize your schema fields (what do you really need for analysis?)\n", "# TODO (A4): define what makes an item unique (id strategy)\n", "\n", "items = [\n", " Item(\n", " id=\"example-1\",\n", " source=\"demo\",\n", " url=\"https://example.com\",\n", " title=\"Example\",\n", " text=\"Hello world\",\n", " fetched_at=now_iso(),\n", " ),\n", " Item(\n", " id=\"example-2\",\n", " source=\"demo\",\n", " url=\"https://example.com/2\",\n", " title=\"Example 2\",\n", " text=\"Another item\",\n", " fetched_at=now_iso(),\n", " ),\n", "]\n", "\n", "# Write JSON Lines (1 JSON object per line)\n", "with SAMPLES_PATH.open(\"w\", encoding=\"utf-8\") as f:\n", " for it in items:\n", " f.write(json.dumps(asdict(it), ensure_ascii=False) + \"\\n\")\n", "\n", "print(f\"Wrote {len(items)} sample items to: {SAMPLES_PATH}\")\n", "\n", "# Read back\n", "read_back = [json.loads(line) for line in SAMPLES_PATH.read_text(encoding=\"utf-8\").splitlines() if line.strip()]\n", "print(read_back[0])\n" ] } ], "metadata": { "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 2 }