leetcode: Claude writes post-mortem and cards

Drop the explain-back exit and the opening-belief question. Once code
passes the examples (or kuhy says done), the coach writes the post-mortem
from the transcript, builds the cards, and appends missing toolbox entries
itself; toolbox_cards add gains --define for new vocabulary properties.
Adds the contribution technique entry from sum-of-all-odd-length-subarrays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWTVKrxg1PGVP4wc6W
This commit is contained in:
Krzysztof Rudnicki 2026-11-20 15:27:42 +01:00
parent c6725351cd
commit 5e69f01472
6 changed files with 323 additions and 67 deletions

View File

@ -17,4 +17,4 @@ The method:
1. **Constraint** - Turn the hard constraint into a rule for the design. 1. **Constraint** - Turn the hard constraint into a rule for the design.
2. **Requirements** - List what the operation must do, as properties, never by name. 2. **Requirements** - List what the operation must do, as properties, never by name.
3. **Toolbox** - Search the toolbox for an operation with those properties. 3. **Toolbox** - Search the toolbox for an operation with those properties.
4. **Post-mortem** - Say which hint gave which requirement, then make the cards. 4. **Post-mortem** - Claude says which hint gave which requirement and makes the cards.

View File

@ -156,22 +156,20 @@ Rules:
## 5. Exit ## 5. Exit
The session is done when kuhy says solved/done **and** explains the The session is done when kuhy's code passes the statement's examples (you
solution back in ≤2 sentences that mention the key mechanism. If the ran it, section 4) or kuhy says solved/done. Ask nothing more: no
explanation is wrong, that is one more H0 turn, not a failure. explain-back, no "what is wrong with your opening belief" (kuhy dropped both
2026-11-20). Go straight to the post-mortem in the same reply.
Then close the loop on the *original* confusion: quote the belief they ## 5b. Post-mortem: written by you, then property cards
opened with ("cancel stops the function at a random place") and ask what
is wrong with it now. A passing submission does not retire a misconception;
only a corrected sentence from them does.
## 5b. Post-mortem: requirement list, then property cards kuhy writes nothing here; you write it from this session's transcript.
After the loop is closed, in the same reply: 1. Post-mortem, ≤5 lines of plain prose: the requirement list as
*properties* (what must vanish, what must survive, how much space); for
1. Ask kuhy for the requirement list as *properties* (what must vanish, what each hint rung kuhy saw, which requirement it handed over; which steps
must survive, how much space), not code or an operation name; then, for kuhy found and which you supplied (bluntly, no comfort); and the answer
every hint rung kuhy saw, which requirement that hint handed over. to the belief kuhy opened with (quote it, say what was wrong with it).
2. Cards are **property -> operation only** (DOCS-coach-spec.md decision 11): one 2. Cards are **property -> operation only** (DOCS-coach-spec.md decision 11): one
per toolbox entry the solution relied on, generated from `toolbox.json` per toolbox entry the solution relied on, generated from `toolbox.json`
(front = its properties, back = its name), in ONE Bash call: (front = its properties, back = its name), in ONE Bash call:
@ -181,16 +179,17 @@ After the loop is closed, in the same reply:
``` ```
Names or aliases, 1-6 per call. They all share the slug `toolbox`, so Names or aliases, 1-6 per call. They all share the slug `toolbox`, so
never `--replace` here: it would delete every other entry's card. never `--replace` here: it would delete every other entry's card.
3. An operation kuhy named that is **not** in the toolbox: propose its 3. An operation the solution relied on that is **not** in the toolbox: pick
properties from the `toolbox.json` vocabulary and ask kuhy to confirm or its properties from the `toolbox.json` vocabulary yourself (`--define
correct them. Only after kuhy confirms, append it (`append_entry`) -- "P=meaning"` for one it lacks) and append it,
never on your own judgement, never with unconfirmed properties: then build its card as in step 2. List each added entry with its
properties so kuhy can veto it:
```bash ```bash
python3 -m leetcode_coach.toolbox_cards add "<name>" --alias "<alias>" \ python3 -m leetcode_coach.toolbox_cards add "<name>" --alias "<alias>" \
--property "<prop>" --property "<prop>" --property "<prop>" --property "<prop>"
``` ```
Refused because the set nests with another entry's? Ask kuhy which Refused because the set nests with another entry's? Add the property
property tells the two apart. Then build its card as in step 2. that tells the two apart.
4. Relay the builder's stdout verbatim -- as markdown, NOT inside a code 4. Relay the builder's stdout verbatim -- as markdown, NOT inside a code
fence (the table must render): the table and the delivery line. fence (the table must render): the table and the delivery line.
If Anki desktop is open (AnkiConnect) the cards are already in deck If Anki desktop is open (AnkiConnect) the cards are already in deck

View File

@ -48,7 +48,7 @@ STEPS = (
"List what the operation must do, as properties, never by name.", "List what the operation must do, as properties, never by name.",
), ),
Step("Toolbox", "Search the toolbox for an operation with those properties."), Step("Toolbox", "Search the toolbox for an operation with those properties."),
Step("Post-mortem", "Say which hint gave which requirement, then make the cards."), Step("Post-mortem", "Claude says which hint gave which requirement and makes the cards."),
) )
NEXT_NOTE = ( NEXT_NOTE = (
"The command skips problems LeetCode already shows as Accepted, " "The command skips problems LeetCode already shows as Accepted, "

View File

@ -196,3 +196,48 @@ def test_cli_without_a_command_prints_usage(
with pytest.raises(SystemExit): with pytest.raises(SystemExit):
toolbox_cards.main([]) toolbox_cards.main([])
assert "usage" in capsys.readouterr().err assert "usage" in capsys.readouterr().err
def test_append_entry_defines_new_properties(box: Path) -> None:
meaning = "each item's share of the total is counted, not rebuilt"
toolbox_cards.append_entry(
"trie",
[],
["counted shares", "greedy"],
path=box,
definitions={"counted shares": meaning},
)
data = toolbox.load(box)
assert data["properties"]["counted shares"] == meaning
assert data["entries"][-1]["properties"] == ["counted shares", "greedy"]
@pytest.mark.parametrize(
("definitions", "error"),
[
({"greedy": "x"}, "already defined: greedy"),
({"new one": " "}, "empty meaning: new one"),
({"unused one": "x"}, "defined but not used: unused one"),
],
)
def test_append_entry_refuses_bad_definitions(
box: Path, definitions: dict[str, str], error: str
) -> None:
before = box.read_text(encoding="utf-8")
with pytest.raises(ValueError, match=error):
toolbox_cards.append_entry(
"trie", [], ["new one", "greedy"], path=box, definitions=definitions
)
assert box.read_text(encoding="utf-8") == before
def test_cli_add_define_adds_a_property(
box: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
monkeypatch.setattr(toolbox, "TOOLBOX_PATH", box)
args = ["add", "trie", "--property", "counted shares", "--property", "greedy"]
assert toolbox_cards.main([*args, "--define", "counted shares=a b"]) == 0
assert "added 'trie'" in capsys.readouterr().out
assert toolbox.load(box)["properties"]["counted shares"] == "a b"
assert toolbox_cards.main(["add", "t2", "--property", "p", "--define", "p"]) == 1
assert "name=meaning" in capsys.readouterr().err

View File

@ -39,108 +39,285 @@
"earliest end first": "choosing the interval that ends first leaves the most room for the rest", "earliest end first": "choosing the interval that ends first leaves the most room for the rest",
"greedy": "commits to the locally best choice and never revisits it", "greedy": "commits to the locally best choice and never revisits it",
"O(log n) push and pop-min": "insert and remove-the-smallest each cost about log n; flip the comparison for largest", "O(log n) push and pop-min": "insert and remove-the-smallest each cost about log n; flip the comparison for largest",
"partial order": "only the top element is guaranteed to be in place; the rest is in no particular order" "partial order": "only the top element is guaranteed to be in place; the rest is in no particular order",
"counts each element's share": "the total is built from each element's value times how many ranges contain it, never by building the ranges"
}, },
"entries": [ "entries": [
{ {
"name": "XOR", "name": "XOR",
"aliases": ["^", "exclusive or", "bitwise xor"], "aliases": [
"properties": ["self-inverse", "invertible", "commutative", "associative", "identity element", "works per bit"] "^",
"exclusive or",
"bitwise xor"
],
"properties": [
"self-inverse",
"invertible",
"commutative",
"associative",
"identity element",
"works per bit"
]
}, },
{ {
"name": "sum / difference", "name": "sum / difference",
"aliases": ["running sum", "subtract to undo", "Gauss sum formula"], "aliases": [
"properties": ["invertible", "commutative", "associative", "identity element", "carries between bits"] "running sum",
"subtract to undo",
"Gauss sum formula"
],
"properties": [
"invertible",
"commutative",
"associative",
"identity element",
"carries between bits"
]
}, },
{ {
"name": "min / max", "name": "min / max",
"aliases": ["Math.max", "Math.min", "running max", "running min"], "aliases": [
"properties": ["commutative", "associative", "identity element", "idempotent", "selective"] "Math.max",
"Math.min",
"running max",
"running min"
],
"properties": [
"commutative",
"associative",
"identity element",
"idempotent",
"selective"
]
}, },
{ {
"name": "gcd", "name": "gcd",
"aliases": ["greatest common divisor", "Euclid's algorithm", "Euclidean algorithm"], "aliases": [
"properties": ["commutative", "associative", "identity element", "idempotent", "divides its inputs"] "greatest common divisor",
"Euclid's algorithm",
"Euclidean algorithm"
],
"properties": [
"commutative",
"associative",
"identity element",
"idempotent",
"divides its inputs"
]
}, },
{ {
"name": "per-bit counts mod k", "name": "per-bit counts mod k",
"aliases": ["count each bit mod k", "bit counting mod 3", "ones and twos masks"], "aliases": [
"properties": ["works per bit", "cancels any k-fold repeat", "O(1) extra space"] "count each bit mod k",
"bit counting mod 3",
"ones and twos masks"
],
"properties": [
"works per bit",
"cancels any k-fold repeat",
"O(1) extra space"
]
}, },
{ {
"name": "lowest set bit", "name": "lowest set bit",
"aliases": ["x & -x", "rightmost set bit", "isolate lowest bit"], "aliases": [
"properties": ["isolates one bit"] "x & -x",
"rightmost set bit",
"isolate lowest bit"
],
"properties": [
"isolates one bit"
]
}, },
{ {
"name": "hash map", "name": "hash map",
"aliases": ["hashmap", "hash table", "new Map"], "aliases": [
"properties": ["O(1) lookup", "stores a value per key", "arbitrary keys"] "hashmap",
"hash table",
"new Map"
],
"properties": [
"O(1) lookup",
"stores a value per key",
"arbitrary keys"
]
}, },
{ {
"name": "hash set", "name": "hash set",
"aliases": ["hashset", "new Set", "seen set"], "aliases": [
"properties": ["O(1) lookup", "presence only", "arbitrary keys"] "hashset",
"new Set",
"seen set"
],
"properties": [
"O(1) lookup",
"presence only",
"arbitrary keys"
]
}, },
{ {
"name": "counting array", "name": "counting array",
"aliases": ["frequency array", "count array", "array of 26 counts"], "aliases": [
"properties": ["O(1) lookup", "stores a value per key", "bounded key range"] "frequency array",
"count array",
"array of 26 counts"
],
"properties": [
"O(1) lookup",
"stores a value per key",
"bounded key range"
]
}, },
{ {
"name": "two pointers", "name": "two pointers",
"aliases": ["left and right pointers", "opposite-end pointers"], "aliases": [
"properties": ["two moving indexes", "from both ends", "O(1) extra space"] "left and right pointers",
"opposite-end pointers"
],
"properties": [
"two moving indexes",
"from both ends",
"O(1) extra space"
]
}, },
{ {
"name": "sliding window", "name": "sliding window",
"aliases": ["expanding window", "shrinking window", "variable-size window"], "aliases": [
"properties": ["two moving indexes", "window moves right", "monotone condition"] "expanding window",
"shrinking window",
"variable-size window"
],
"properties": [
"two moving indexes",
"window moves right",
"monotone condition"
]
}, },
{ {
"name": "sorting", "name": "sorting",
"aliases": ["sort first", "Array.prototype.sort", ".sort("], "aliases": [
"properties": ["O(n log n) time", "makes equal values adjacent"] "sort first",
"Array.prototype.sort",
".sort("
],
"properties": [
"O(n log n) time",
"makes equal values adjacent"
]
}, },
{ {
"name": "binary search", "name": "binary search",
"aliases": ["bisect", "lower bound", "halving search"], "aliases": [
"properties": ["needs sorted input", "O(log n) per query"] "bisect",
"lower bound",
"halving search"
],
"properties": [
"needs sorted input",
"O(log n) per query"
]
}, },
{ {
"name": "prefix sums", "name": "prefix sums",
"aliases": ["prefix sum array", "cumulative sum", "running totals array"], "aliases": [
"properties": ["range query in O(1)", "needs an inverse", "keeps every prefix"] "prefix sum array",
"cumulative sum",
"running totals array"
],
"properties": [
"range query in O(1)",
"needs an inverse",
"keeps every prefix"
]
}, },
{ {
"name": "prefix sum + hash map", "name": "prefix sum + hash map",
"aliases": ["map of seen prefix sums", "prefix count map"], "aliases": [
"properties": ["needs an inverse", "single pass", "O(1) lookup", "handles negatives"] "map of seen prefix sums",
"prefix count map"
],
"properties": [
"needs an inverse",
"single pass",
"O(1) lookup",
"handles negatives"
]
}, },
{ {
"name": "Boyer-Moore majority vote", "name": "Boyer-Moore majority vote",
"aliases": ["Boyer–Moore", "majority vote", "candidate and counter"], "aliases": [
"properties": ["needs a majority", "single pass", "O(1) extra space"] "Boyer–Moore",
"majority vote",
"candidate and counter"
],
"properties": [
"needs a majority",
"single pass",
"O(1) extra space"
]
}, },
{ {
"name": "monotonic stack", "name": "monotonic stack",
"aliases": ["monotone stack", "increasing stack", "decreasing stack"], "aliases": [
"properties": ["last-in-first-out", "next-greater lookup", "amortized O(n)"] "monotone stack",
"increasing stack",
"decreasing stack"
],
"properties": [
"last-in-first-out",
"next-greater lookup",
"amortized O(n)"
]
}, },
{ {
"name": "sort by start + merge", "name": "sort by start + merge",
"aliases": ["sort by start", "sort then combine"], "aliases": [
"properties": ["needs sorted input", "overlaps become adjacent", "single pass"] "sort by start",
"sort then combine"
],
"properties": [
"needs sorted input",
"overlaps become adjacent",
"single pass"
]
}, },
{ {
"name": "sort by end + greedy pick", "name": "sort by end + greedy pick",
"aliases": ["sort by end", "interval scheduling", "activity selection"], "aliases": [
"properties": ["needs sorted input", "earliest end first", "greedy"] "sort by end",
"interval scheduling",
"activity selection"
],
"properties": [
"needs sorted input",
"earliest end first",
"greedy"
]
}, },
{ {
"name": "heap", "name": "heap",
"aliases": ["priority queue", "min-heap", "max-heap", "heapq"], "aliases": [
"properties": ["O(log n) push and pop-min", "partial order"] "priority queue",
"min-heap",
"max-heap",
"heapq"
],
"properties": [
"O(log n) push and pop-min",
"partial order"
]
},
{
"name": "contribution technique",
"aliases": [
"count slices containing each element",
"(i+1)*(n-i)"
],
"properties": [
"counts each element's share",
"single pass",
"O(1) extra space"
]
} }
] ]
} }

View File

@ -9,9 +9,10 @@ slug means one note per entry however many problems used it.
python3 -m leetcode_coach.toolbox_cards cards <name|alias>... (stdout -> python3 -m leetcode_coach.toolbox_cards cards <name|alias>... (stdout ->
the JSON make_cards.py reads; pipe it straight in) the JSON make_cards.py reads; pipe it straight in)
python3 -m leetcode_coach.toolbox_cards add <name> [--alias A]... --property P... python3 -m leetcode_coach.toolbox_cards add <name> [--alias A]... --property P...
[--define "P=meaning"]... (a property the vocabulary lacks yet)
``add`` (``append_entry``) is the only writer of toolbox.json and the coach ``add`` (``append_entry``) is the only writer of toolbox.json and the coach
calls it only after kuhy has confirmed the properties. It refuses unknown calls it on its own judgement (kuhy may veto). It refuses unknown
properties, a name or alias already taken, and a property set that nests with properties, a name or alias already taken, and a property set that nests with
an existing entry's (that card would have two right answers). Its printed an existing entry's (that card would have two right answers). Its printed
lines are its interface (T201 exemption in pyproject.toml). lines are its interface (T201 exemption in pyproject.toml).
@ -91,16 +92,37 @@ def _problems(
return problems return problems
def _definition_problems(
vocab: dict[str, str], properties: list[str], definitions: dict[str, str]
) -> list[str]:
"""Why the new vocabulary entries may not be added (empty = ok)."""
problems = [f"already defined: {p}" for p in definitions if p in vocab]
problems += [f"empty meaning: {p}" for p, m in definitions.items() if not m.strip()]
unused = [p for p in definitions if p not in properties]
problems += [f"defined but not used: {p}" for p in unused]
return problems
def append_entry( def append_entry(
name: str, name: str,
aliases: list[str], aliases: list[str],
properties: list[str], properties: list[str],
*, *,
path: Path | None = None, path: Path | None = None,
definitions: dict[str, str] | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
"""Append one confirmed entry to toolbox.json; ValueError if it is refused.""" """Append one entry to toolbox.json; ValueError if it is refused.
``definitions`` adds properties the vocabulary lacks yet (name -> meaning);
each must be new and used by this entry, so the vocabulary never holds an
unused or silently redefined property.
"""
target = toolbox.TOOLBOX_PATH if path is None else path target = toolbox.TOOLBOX_PATH if path is None else path
data = toolbox.load(target) data = toolbox.load(target)
definitions = definitions or {}
if problems := _definition_problems(data["properties"], properties, definitions):
raise ValueError("; ".join(problems))
data["properties"].update(definitions)
if problems := _problems(data, name, aliases, properties): if problems := _problems(data, name, aliases, properties):
raise ValueError("; ".join(problems)) raise ValueError("; ".join(problems))
entry = {"name": name.strip(), "aliases": aliases, "properties": properties} entry = {"name": name.strip(), "aliases": aliases, "properties": properties}
@ -120,15 +142,25 @@ def _parser() -> argparse.ArgumentParser:
sub = parser.add_subparsers(dest="command", required=True) sub = parser.add_subparsers(dest="command", required=True)
cards = sub.add_parser("cards", help="print make_cards.py input for entries") cards = sub.add_parser("cards", help="print make_cards.py input for entries")
cards.add_argument("names", nargs="+") cards.add_argument("names", nargs="+")
add = sub.add_parser("add", help="append an entry kuhy has confirmed") add = sub.add_parser("add", help="append a new toolbox entry")
add.add_argument("name") add.add_argument("name")
add.add_argument("--alias", action="append", default=[]) add.add_argument("--alias", action="append", default=[])
add.add_argument("--property", action="append", default=[], required=True) add.add_argument("--property", action="append", default=[], required=True)
add.add_argument("--define", action="append", default=[], metavar="P=MEANING")
return parser return parser
def _parse_definitions(raw: list[str]) -> dict[str, str]:
"""``["P=meaning", ...]`` as a dict; ValueError on an item without ``=``."""
if bad := [item for item in raw if "=" not in item]:
msg = "--define takes name=meaning, got: " + ", ".join(bad)
raise ValueError(msg)
pairs = (item.split("=", 1) for item in raw)
return {name.strip(): meaning.strip() for name, meaning in pairs}
def main(argv: list[str]) -> int: def main(argv: list[str]) -> int:
"""`cards` prints builder input; `add` appends a confirmed entry.""" """`cards` prints builder input; `add` appends a new entry."""
args = _parser().parse_args(argv) args = _parser().parse_args(argv)
if args.command == "cards": if args.command == "cards":
try: try:
@ -140,7 +172,10 @@ def main(argv: list[str]) -> int:
print(json.dumps({"slug": SLUG, "cards": cards}, ensure_ascii=False)) print(json.dumps({"slug": SLUG, "cards": cards}, ensure_ascii=False))
return 0 return 0
try: try:
entry = append_entry(args.name, args.alias, args.property) definitions = _parse_definitions(args.define)
entry = append_entry(
args.name, args.alias, args.property, definitions=definitions
)
except ValueError as exc: except ValueError as exc:
_logger.warning("toolbox entry refused: %s", exc) _logger.warning("toolbox entry refused: %s", exc)
print(f"not added: {exc}", file=sys.stderr) print(f"not added: {exc}", file=sys.stderr)