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.
2. **Requirements** - List what the operation must do, as properties, never by name.
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
The session is done when kuhy says solved/done **and** explains the
solution back in ≤2 sentences that mention the key mechanism. If the
explanation is wrong, that is one more H0 turn, not a failure.
The session is done when kuhy's code passes the statement's examples (you
ran it, section 4) or kuhy says solved/done. Ask nothing more: no
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
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: written by you, then property cards
## 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. Ask kuhy for the requirement list as *properties* (what must vanish, what
must survive, how much space), not code or an operation name; then, for
every hint rung kuhy saw, which requirement that hint handed over.
1. Post-mortem, ≤5 lines of plain prose: the requirement list as
*properties* (what must vanish, what must survive, how much space); for
each hint rung kuhy saw, which requirement it handed over; which steps
kuhy found and which you supplied (bluntly, no comfort); and the answer
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
per toolbox entry the solution relied on, generated from `toolbox.json`
(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
never `--replace` here: it would delete every other entry's card.
3. An operation kuhy named that is **not** in the toolbox: propose its
properties from the `toolbox.json` vocabulary and ask kuhy to confirm or
correct them. Only after kuhy confirms, append it (`append_entry`) --
never on your own judgement, never with unconfirmed properties:
3. An operation the solution relied on that is **not** in the toolbox: pick
its properties from the `toolbox.json` vocabulary yourself (`--define
"P=meaning"` for one it lacks) and append it,
then build its card as in step 2. List each added entry with its
properties so kuhy can veto it:
```bash
python3 -m leetcode_coach.toolbox_cards add "<name>" --alias "<alias>" \
--property "<prop>" --property "<prop>"
```
Refused because the set nests with another entry's? Ask kuhy which
property tells the two apart. Then build its card as in step 2.
Refused because the set nests with another entry's? Add the property
that tells the two apart.
4. Relay the builder's stdout verbatim -- as markdown, NOT inside a code
fence (the table must render): the table and the delivery line.
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.",
),
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 = (
"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):
toolbox_cards.main([])
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",
"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",
"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": [
{
"name": "XOR",
"aliases": ["^", "exclusive or", "bitwise xor"],
"properties": ["self-inverse", "invertible", "commutative", "associative", "identity element", "works per bit"]
"aliases": [
"^",
"exclusive or",
"bitwise xor"
],
"properties": [
"self-inverse",
"invertible",
"commutative",
"associative",
"identity element",
"works per bit"
]
},
{
"name": "sum / difference",
"aliases": ["running sum", "subtract to undo", "Gauss sum formula"],
"properties": ["invertible", "commutative", "associative", "identity element", "carries between bits"]
"aliases": [
"running sum",
"subtract to undo",
"Gauss sum formula"
],
"properties": [
"invertible",
"commutative",
"associative",
"identity element",
"carries between bits"
]
},
{
"name": "min / max",
"aliases": ["Math.max", "Math.min", "running max", "running min"],
"properties": ["commutative", "associative", "identity element", "idempotent", "selective"]
"aliases": [
"Math.max",
"Math.min",
"running max",
"running min"
],
"properties": [
"commutative",
"associative",
"identity element",
"idempotent",
"selective"
]
},
{
"name": "gcd",
"aliases": ["greatest common divisor", "Euclid's algorithm", "Euclidean algorithm"],
"properties": ["commutative", "associative", "identity element", "idempotent", "divides its inputs"]
"aliases": [
"greatest common divisor",
"Euclid's algorithm",
"Euclidean algorithm"
],
"properties": [
"commutative",
"associative",
"identity element",
"idempotent",
"divides its inputs"
]
},
{
"name": "per-bit counts mod k",
"aliases": ["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"]
"aliases": [
"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",
"aliases": ["x & -x", "rightmost set bit", "isolate lowest bit"],
"properties": ["isolates one bit"]
"aliases": [
"x & -x",
"rightmost set bit",
"isolate lowest bit"
],
"properties": [
"isolates one bit"
]
},
{
"name": "hash map",
"aliases": ["hashmap", "hash table", "new Map"],
"properties": ["O(1) lookup", "stores a value per key", "arbitrary keys"]
"aliases": [
"hashmap",
"hash table",
"new Map"
],
"properties": [
"O(1) lookup",
"stores a value per key",
"arbitrary keys"
]
},
{
"name": "hash set",
"aliases": ["hashset", "new Set", "seen set"],
"properties": ["O(1) lookup", "presence only", "arbitrary keys"]
"aliases": [
"hashset",
"new Set",
"seen set"
],
"properties": [
"O(1) lookup",
"presence only",
"arbitrary keys"
]
},
{
"name": "counting array",
"aliases": ["frequency array", "count array", "array of 26 counts"],
"properties": ["O(1) lookup", "stores a value per key", "bounded key range"]
"aliases": [
"frequency array",
"count array",
"array of 26 counts"
],
"properties": [
"O(1) lookup",
"stores a value per key",
"bounded key range"
]
},
{
"name": "two pointers",
"aliases": ["left and right pointers", "opposite-end pointers"],
"properties": ["two moving indexes", "from both ends", "O(1) extra space"]
"aliases": [
"left and right pointers",
"opposite-end pointers"
],
"properties": [
"two moving indexes",
"from both ends",
"O(1) extra space"
]
},
{
"name": "sliding window",
"aliases": ["expanding window", "shrinking window", "variable-size window"],
"properties": ["two moving indexes", "window moves right", "monotone condition"]
"aliases": [
"expanding window",
"shrinking window",
"variable-size window"
],
"properties": [
"two moving indexes",
"window moves right",
"monotone condition"
]
},
{
"name": "sorting",
"aliases": ["sort first", "Array.prototype.sort", ".sort("],
"properties": ["O(n log n) time", "makes equal values adjacent"]
"aliases": [
"sort first",
"Array.prototype.sort",
".sort("
],
"properties": [
"O(n log n) time",
"makes equal values adjacent"
]
},
{
"name": "binary search",
"aliases": ["bisect", "lower bound", "halving search"],
"properties": ["needs sorted input", "O(log n) per query"]
"aliases": [
"bisect",
"lower bound",
"halving search"
],
"properties": [
"needs sorted input",
"O(log n) per query"
]
},
{
"name": "prefix sums",
"aliases": ["prefix sum array", "cumulative sum", "running totals array"],
"properties": ["range query in O(1)", "needs an inverse", "keeps every prefix"]
"aliases": [
"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",
"aliases": ["map of seen prefix sums", "prefix count map"],
"properties": ["needs an inverse", "single pass", "O(1) lookup", "handles negatives"]
"aliases": [
"map of seen prefix sums",
"prefix count map"
],
"properties": [
"needs an inverse",
"single pass",
"O(1) lookup",
"handles negatives"
]
},
{
"name": "Boyer-Moore majority vote",
"aliases": ["Boyer–Moore", "majority vote", "candidate and counter"],
"properties": ["needs a majority", "single pass", "O(1) extra space"]
"aliases": [
"Boyer–Moore",
"majority vote",
"candidate and counter"
],
"properties": [
"needs a majority",
"single pass",
"O(1) extra space"
]
},
{
"name": "monotonic stack",
"aliases": ["monotone stack", "increasing stack", "decreasing stack"],
"properties": ["last-in-first-out", "next-greater lookup", "amortized O(n)"]
"aliases": [
"monotone stack",
"increasing stack",
"decreasing stack"
],
"properties": [
"last-in-first-out",
"next-greater lookup",
"amortized O(n)"
]
},
{
"name": "sort by start + merge",
"aliases": ["sort by start", "sort then combine"],
"properties": ["needs sorted input", "overlaps become adjacent", "single pass"]
"aliases": [
"sort by start",
"sort then combine"
],
"properties": [
"needs sorted input",
"overlaps become adjacent",
"single pass"
]
},
{
"name": "sort by end + greedy pick",
"aliases": ["sort by end", "interval scheduling", "activity selection"],
"properties": ["needs sorted input", "earliest end first", "greedy"]
"aliases": [
"sort by end",
"interval scheduling",
"activity selection"
],
"properties": [
"needs sorted input",
"earliest end first",
"greedy"
]
},
{
"name": "heap",
"aliases": ["priority queue", "min-heap", "max-heap", "heapq"],
"properties": ["O(log n) push and pop-min", "partial order"]
"aliases": [
"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 ->
the JSON make_cards.py reads; pipe it straight in)
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
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
an existing entry's (that card would have two right answers). Its printed
lines are its interface (T201 exemption in pyproject.toml).
@ -91,16 +92,37 @@ def _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(
name: str,
aliases: list[str],
properties: list[str],
*,
path: Path | None = None,
definitions: dict[str, str] | None = None,
) -> 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
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):
raise ValueError("; ".join(problems))
entry = {"name": name.strip(), "aliases": aliases, "properties": properties}
@ -120,15 +142,25 @@ def _parser() -> argparse.ArgumentParser:
sub = parser.add_subparsers(dest="command", required=True)
cards = sub.add_parser("cards", help="print make_cards.py input for entries")
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("--alias", action="append", default=[])
add.add_argument("--property", action="append", default=[], required=True)
add.add_argument("--define", action="append", default=[], metavar="P=MEANING")
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:
"""`cards` prints builder input; `add` appends a confirmed entry."""
"""`cards` prints builder input; `add` appends a new entry."""
args = _parser().parse_args(argv)
if args.command == "cards":
try:
@ -140,7 +172,10 @@ def main(argv: list[str]) -> int:
print(json.dumps({"slug": SLUG, "cards": cards}, ensure_ascii=False))
return 0
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:
_logger.warning("toolbox entry refused: %s", exc)
print(f"not added: {exc}", file=sys.stderr)