#!/usr/bin/env python3 """Split the answers appendix into one Markdown file per chapter. Reads Markdown/Appendices.md (the "Answers to Selected Exercises" section) and writes: Answers/README.md Answers/Chapter_01_Answers.md ... Answers/Chapter_16_Answers.md The HTML site is then produced from those Markdown files by build.py. Run this again whenever the appendix changes: python3 site_builder/split_answers.py python3 site_builder/build.py """ from __future__ import annotations import re from pathlib import Path ROOT = Path(__file__).resolve().parent.parent APPENDICES = ROOT / "Markdown" / "Appendices.md" OUT = ROOT / "Answers" HEADING = "## Answers to Selected Exercises" def chapter_topics() -> dict[int, str]: """Chapter numbers and titles from the book's contents table.""" text = (ROOT / "Markdown" / "README.md").read_text(encoding="utf-8") topics: dict[int, str] = {} for line in text.splitlines(): match = re.match( r"\|\s*\[Chapter_(\d+)\.md\]\([^)]+\)\s*\|\s*([^|]+?)\s*\|\s*([^|]+?)\s*\|", line, ) if match: topics[int(match.group(1))] = match.group(3).strip() return topics def answers_section() -> list[str]: lines = APPENDICES.read_text(encoding="utf-8").splitlines() try: start = next(i for i, line in enumerate(lines) if line.strip() == HEADING) except StopIteration: raise SystemExit(f"could not find {HEADING!r} in {APPENDICES}") end = len(lines) for i in range(start + 1, len(lines)): if lines[i].startswith("## "): end = i break return lines[start + 1:end] def split_by_chapter(lines: list[str]) -> dict[int, list[str]]: chapters: dict[int, list[str]] = {} current: int | None = None for line in lines: match = re.match(r"^### Chapter (\d+), (.*)$", line) if match: current = int(match.group(1)) chapters.setdefault(current, []).append("## " + match.group(2).strip()) elif current is not None: # The appendix images live in Markdown/figures; fix the relative path # for the new Answers/ folder. line = re.sub(r"\]\((figures/[^)]+)\)", r"](../Markdown/\1)", line) line = re.sub(r'src="(figures/[^"]+)"', r'src="../Markdown/\1"', line) chapters[current].append(line) return chapters def chapter_preamble(number: int, title: str) -> list[str]: return [ f"# Chapter {number} — Answers", "", f"Selected answers for **Chapter {number}: {title}**, transcribed from the " "book's appendix. They are meant for checking your work, not for copying — " "the book prints answers to selected exercises only.", "", f"Back to [Chapter {number}](../Markdown/Chapter_{number:02d}.md) · " f"Teacher’s answers: [Chapter {number}](../Teacher_Answers/Chapter_{number:02d}.md) · " "Complete key: [Answers to Exercises PDF]" "(../Other/Teacher's%20Guide_Answers.pdf) · " "Printed answers: [appendices PDF](../Geometry_Appendices.pdf#page=20)", "", ] def main() -> int: section = answers_section() chapters = split_by_chapter(section) topics = chapter_topics() OUT.mkdir(exist_ok=True) for number in sorted(chapters): title = topics.get(number, "") body = "\n".join(chapters[number]).strip("\n") text = "\n".join(chapter_preamble(number, title)) + "\n" + body + "\n" (OUT / f"Chapter_{number:02d}_Answers.md").write_text(text, encoding="utf-8") rows = [] for number in sorted(chapters): title = topics.get(number, "") rows.append( f"| {number} | {title} | " f"[Answers](Chapter_{number:02d}_Answers.md) |" ) readme = "\n".join( [ "# Answers to Selected Exercises", "", "The book's selected answers, split into **one Markdown page per chapter** " "so each set can be read next to its lesson. The answers are the ones " "printed in the appendix; the textbook does not print every exercise.", "", "For the complete answer key, with commentary, see the " "[Teacher’s Guide answers](../Teacher_Answers/index.md) or the " "[Answers to Exercises PDF](../Other/Teacher's%20Guide_Answers.pdf) " "(288 pages). The printed appendix answers also appear " "in the [appendices PDF](../Geometry_Appendices.pdf#page=20).", "", "## Chapters", "", "| Chapter | Topic | Answers |", "|---|---|---|", *rows, "", "## Source", "", "These pages are generated from `Markdown/Appendices.md` by " "`site_builder/split_answers.py`. Edit the appendix and re-run the " "splitter to update them.", "", ] ) (OUT / "README.md").write_text(readme, encoding="utf-8") print(f"wrote {len(chapters)} chapter files + README.md to {OUT}") return 0 if __name__ == "__main__": raise SystemExit(main())