mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-20 18:32:30 +01:00
Merge leetcode coach changes from local main
This commit is contained in:
commit
0e22457246
@ -3,8 +3,8 @@
|
||||
Moved out of `SKILL.md` (250-line cap); none of it is coaching instruction.
|
||||
|
||||
The right client is `leetcode <url>` (this package's `leetcode` launcher,
|
||||
symlinked from `~/.local/bin`): a print-mode loop on sonnet
|
||||
(`LEETCODE_MODEL=opus` or `fable` to switch) that also runs
|
||||
symlinked from `~/.local/bin`): a print-mode loop on opus
|
||||
(`LEETCODE_MODEL=sonnet` or `fable` to switch) that also runs
|
||||
the req-before-code gate and the session log (`leetcode report`). The Stop
|
||||
hook (`stop_gate.py`) sends back a reply with a pasteable line or an early
|
||||
toolbox name, but the TUI has already streamed it (2026-09-21: the blocked
|
||||
|
||||
@ -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.
|
||||
|
||||
@ -112,7 +112,7 @@ Rules:
|
||||
drop back one rung, ask something smaller. "I don't understand the
|
||||
question" means the *wording* failed: rephrase once with a concrete
|
||||
example, same step. Never repeat the same question rephrased twice.
|
||||
- **Turn budget.** Easy ≈ 16 kuhy turns, Medium ≈ 24, Hard ≈ 32. Past it,
|
||||
- **Turn budget.** Easy ≈ 32 kuhy turns, Medium ≈ 48, Hard ≈ 64. Past it,
|
||||
sum up in ≤2 lines what kuhy has established and ask for a full attempt.
|
||||
- **Frustration = stop the ladder.** "going in circles", "jesus", "stop",
|
||||
"this is too complicated", or two "I don't understand": no further
|
||||
@ -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
|
||||
|
||||
@ -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, "
|
||||
|
||||
@ -104,7 +104,7 @@ def start_session(problem: list[str], *, local: bool) -> int:
|
||||
opener = local_session.opening_message(problem[1:])
|
||||
gate = phase.PhaseGate.open(problem[0])
|
||||
return local_session.run(problem[0], [], opener, read_block, gate=gate)
|
||||
return run_claude(os.environ.get("LEETCODE_MODEL", "sonnet"), problem)
|
||||
return run_claude(os.environ.get("LEETCODE_MODEL", "opus"), problem)
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
@ -115,7 +115,7 @@ def main(argv: list[str]) -> int:
|
||||
return report.main(args[1:])
|
||||
if not args or args[0] in {"-h", "--help"}:
|
||||
print("Usage: leetcode [--local] <url-or-slug> [what you are stuck on...]")
|
||||
print(" LEETCODE_MODEL=opus|fable leetcode ... (default: sonnet)")
|
||||
print(" LEETCODE_MODEL=sonnet|fable leetcode ... (default: opus)")
|
||||
print(" --local coach on the local Ollama model (free, offline)")
|
||||
print(" leetcode due | --cluster <name> | --retest <slug> (--dry-run)")
|
||||
print(" leetcode report req-before-code, max rung, reveal per problem")
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
"""The coaching chat: the CLI's sonnet session, one per problem.
|
||||
"""The coaching chat: the CLI's opus session, one per problem.
|
||||
|
||||
The same session `leetcode_repl.run_claude` runs: it opens with
|
||||
``/leetcode <slug>`` (which loads SKILL.md and arms the no-solution Stop
|
||||
@ -43,8 +43,8 @@ TurnError = CoachError
|
||||
|
||||
|
||||
def model() -> str:
|
||||
"""The coaching model (``LEETCODE_MODEL``, default sonnet, as the REPL)."""
|
||||
return os.environ.get("LEETCODE_MODEL") or "sonnet"
|
||||
"""The coaching model (``LEETCODE_MODEL``, default opus, as the REPL)."""
|
||||
return os.environ.get("LEETCODE_MODEL") or "opus"
|
||||
|
||||
|
||||
def _env(session: Session) -> dict[str, str]:
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
"""Judge kuhy's requirement list, and ambiguous code, on a cheap model.
|
||||
|
||||
DOCS-coach-spec.md decision 5: a separate ``claude -p --model haiku`` call (the
|
||||
coaching session stays on sonnet), Ollama through `local_backend` when haiku
|
||||
coaching session stays on opus), Ollama through `local_backend` when haiku
|
||||
is out of quota, errors or answers something that is not the JSON asked for,
|
||||
and when neither answers the gate fails OPEN: ``unverified``, kuhy continues.
|
||||
|
||||
|
||||
@ -241,6 +241,6 @@ def test_repl_main_dispatches_cluster_commands(
|
||||
monkeypatch.setattr(local_session, "run", fake_local)
|
||||
monkeypatch.setattr(cluster_cli, "accepted_on_leetcode", never)
|
||||
assert leetcode_repl.main(["--cluster", "intervals"]) == 0
|
||||
assert started == [("sonnet", ["merge-intervals"])]
|
||||
assert started == [("opus", ["merge-intervals"])]
|
||||
assert leetcode_repl.main(["--local", "--cluster", "intervals"]) == 0
|
||||
assert handed == ["merge-intervals"]
|
||||
|
||||
@ -129,12 +129,12 @@ def test_read_block_joins_lines_until_a_blank(
|
||||
assert leetcode_repl.read_block() == "x"
|
||||
|
||||
|
||||
def test_repl_defaults_to_sonnet(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
def test_repl_defaults_to_opus(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
seen: list[str] = []
|
||||
monkeypatch.delenv("LEETCODE_MODEL", raising=False)
|
||||
monkeypatch.setattr(leetcode_repl, "run_claude", lambda m, _a: seen.append(m))
|
||||
leetcode_repl.main(["two-sum"])
|
||||
assert seen == ["sonnet"]
|
||||
assert seen == ["opus"]
|
||||
|
||||
|
||||
def test_local_flag_skips_claude(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
@ -179,3 +179,10 @@ def test_launcher_does_not_leak_pythonpath_into_the_session() -> None:
|
||||
"""The REPL hands its environment to `claude -p`; the launcher adds nothing."""
|
||||
body = LAUNCHER.read_text(encoding="utf-8").split("set -euo pipefail", 1)[1]
|
||||
assert "PYTHONPATH" not in body
|
||||
|
||||
|
||||
def test_relay_chat_defaults_to_opus(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
from leetcode_coach.relay import chat
|
||||
|
||||
monkeypatch.delenv("LEETCODE_MODEL", raising=False)
|
||||
assert chat.model() == "opus"
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@ -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)
|
||||
|
||||
Loading…
Reference in New Issue
Block a user