usaco new <leetcode-link> (alias: from) and usaco daily fetch a problem from LeetCode's GraphQL API and write problem.md, main.cpp (template header + LeetCode's C++ starter), a generated driver.h that runs the solution on LeetCode-format input, and the examples as tests with the expected outputs from the statement. leetcode.h holds ListNode/TreeNode and the parse/print helpers; everything local sits behind #ifdef LOCAL so main.cpp stays submittable. reset re-fetches the starter code for LeetCode problems, the REPL's new selects the imported problem, and usaco.zsh turns off globbing so a pasted ?envType=... link works unquoted. Co-Authored-By: Claude Opus 5.5 <[email protected]>
478 lines
17 KiB
Python
478 lines
17 KiB
Python
"""leetcode.py - import a LeetCode problem into solving/<slug>/.
|
|
|
|
Usage: python3 -I lib/leetcode.py ROOT <url|slug|daily> [--main-only]
|
|
|
|
Asks LeetCode's public GraphQL API (the one the problem page uses) for the
|
|
problem and writes:
|
|
problem.md the statement as markdown, like the website's statement fetch
|
|
.url the problem link
|
|
main.cpp template.cpp's header + LeetCode's C++ starter code
|
|
driver.h a generated main() (LOCAL builds only) that reads <slug>.in in
|
|
LeetCode's testcase format, calls the solution, and prints
|
|
answers the way LeetCode does -- see leetcode.h
|
|
<slug>.in every example, back to back (what 'usaco run' feeds it)
|
|
tests/N.in/out one example each, expected output taken from the statement
|
|
|
|
--main-only rewrites just main.cpp in an existing problem dir (usaco reset).
|
|
Progress goes to stderr; the problem's name is the only thing on stdout.
|
|
"""
|
|
|
|
import html
|
|
import json
|
|
import re
|
|
import sys
|
|
import urllib.error
|
|
import urllib.request
|
|
from html.parser import HTMLParser
|
|
from pathlib import Path
|
|
|
|
API = "https://leetcode.com/graphql"
|
|
|
|
QUESTION = """query($s: String!) { question(titleSlug: $s) {
|
|
questionFrontendId title titleSlug content isPaidOnly
|
|
exampleTestcaseList metaData codeSnippets { langSlug code } } }"""
|
|
|
|
DAILY = "query { activeDailyCodingChallengeQuestion { question { titleSlug } } }"
|
|
|
|
|
|
def die(msg):
|
|
print(f"Error: {msg}", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
|
|
def graphql(query, variables=None):
|
|
body = json.dumps({"query": query, "variables": variables or {}}).encode()
|
|
req = urllib.request.Request(API, data=body, headers={
|
|
"Content-Type": "application/json",
|
|
"Referer": "https://leetcode.com",
|
|
"User-Agent": "Mozilla/5.0 (usaco cli)",
|
|
})
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=15) as resp:
|
|
return json.load(resp)["data"]
|
|
except urllib.error.HTTPError as e:
|
|
die(f"leetcode.com answered {e.code}")
|
|
except (urllib.error.URLError, TimeoutError) as e:
|
|
die(f"could not reach leetcode.com ({e})")
|
|
|
|
|
|
def slug_of(arg):
|
|
if arg == "daily":
|
|
q = graphql(DAILY)["activeDailyCodingChallengeQuestion"]["question"]
|
|
return q["titleSlug"]
|
|
# https://leetcode.com/problems/<slug>/description/?envType=...
|
|
m = re.search(r"leetcode\.com/problems/([\w-]+)", arg)
|
|
if m:
|
|
return m.group(1)
|
|
if re.fullmatch(r"[a-z0-9-]+", arg):
|
|
return arg
|
|
die(f"not a LeetCode problem link: {arg}")
|
|
|
|
|
|
# ----- statement -----
|
|
|
|
class Markdown(HTMLParser):
|
|
"""LeetCode statements use a small slice of HTML; this covers it."""
|
|
|
|
INLINE = {"strong": "**", "b": "**", "em": "*", "i": "*", "code": "`"}
|
|
|
|
def __init__(self):
|
|
super().__init__(convert_charrefs=True)
|
|
self.bufs = [[]] # one buffer per open inline element
|
|
self.pre = False
|
|
self.lists = [] # [tag, items so far] per open <ul>/<ol>
|
|
self.href = None
|
|
|
|
def out(self, s):
|
|
self.bufs[-1].append(s)
|
|
|
|
def block(self):
|
|
self.out("\n\n")
|
|
|
|
def handle_starttag(self, tag, attrs):
|
|
a = dict(attrs)
|
|
if tag in self.INLINE or tag == "a":
|
|
self.bufs.append([])
|
|
if tag == "a":
|
|
self.href = a.get("href")
|
|
elif tag in ("p", "div"):
|
|
self.block()
|
|
elif tag == "pre":
|
|
self.block()
|
|
self.out("```\n")
|
|
self.pre = True
|
|
elif tag in ("ul", "ol"):
|
|
self.block()
|
|
self.lists.append([tag, 0])
|
|
elif tag == "li" and self.lists:
|
|
self.lists[-1][1] += 1
|
|
kind, n = self.lists[-1]
|
|
indent = " " * (len(self.lists) - 1)
|
|
self.out(f"\n{indent}" + ("- " if kind == "ul" else f"{n}. "))
|
|
elif tag == "br":
|
|
self.out("\n" if self.pre else " \n")
|
|
elif tag == "sup":
|
|
self.out("^")
|
|
elif tag == "img":
|
|
self.out(f"})")
|
|
|
|
def handle_endtag(self, tag):
|
|
if (tag in self.INLINE or tag == "a") and len(self.bufs) > 1:
|
|
text = "".join(self.bufs.pop())
|
|
core = text.strip()
|
|
if tag == "a":
|
|
text = text.replace(core, f"[{core}]({self.href})") if core and self.href else text
|
|
elif core and not self.pre:
|
|
mark = self.INLINE[tag]
|
|
# keep surrounding spaces outside the markers: "** x **" isn't bold
|
|
text = text.replace(core, f"{mark}{core}{mark}", 1)
|
|
self.out(text)
|
|
elif tag == "pre":
|
|
body = "".join(self.bufs[-1])
|
|
self.bufs[-1][:] = [body.rstrip() + "\n```"]
|
|
self.pre = False
|
|
self.block()
|
|
elif tag in ("ul", "ol") and self.lists:
|
|
self.lists.pop()
|
|
self.block()
|
|
elif tag in ("p", "div"):
|
|
self.block()
|
|
|
|
def handle_data(self, data):
|
|
if not self.pre:
|
|
data = re.sub(r"\s+", " ", data)
|
|
self.out(data.replace("\xa0", " "))
|
|
|
|
def text(self):
|
|
while len(self.bufs) > 1: # unclosed inline tags
|
|
self.handle_endtag("code")
|
|
md = "".join(self.bufs[0])
|
|
md = "\n".join(line.rstrip() if not line.endswith(" ") else line for line in md.split("\n"))
|
|
parts = md.split("```") # even parts: prose, odd parts: code blocks
|
|
for i in range(len(parts)):
|
|
if i % 2: # no blank first line in a code block
|
|
parts[i] = re.sub(r"^\n\n+", "\n", parts[i])
|
|
else: # no stray space starting a line, at most one blank line
|
|
parts[i] = re.sub(r"\n{3,}", "\n\n", re.sub(r"\n (?=\S)", "\n", parts[i]))
|
|
return "```".join(parts).strip()
|
|
|
|
|
|
def to_markdown(content):
|
|
p = Markdown()
|
|
p.feed(content)
|
|
p.close()
|
|
return p.text()
|
|
|
|
|
|
def plain_text(content):
|
|
"""The statement with tags stripped, one line per block."""
|
|
text = re.sub(r"<(br|/p|/div|/pre|/li)\b[^>]*>", "\n", content)
|
|
text = html.unescape(re.sub(r"<[^>]+>", "", text)).replace("\xa0", " ")
|
|
return text
|
|
|
|
|
|
def minify(value):
|
|
"""Drop whitespace outside string literals: '[null, 1]' -> '[null,1]'."""
|
|
out, in_str, esc = [], False, False
|
|
for c in value:
|
|
if in_str:
|
|
out.append(c)
|
|
in_str = not (c == '"' and not esc)
|
|
esc = c == "\\" and not esc
|
|
elif c == '"':
|
|
out.append(c)
|
|
in_str = True
|
|
elif not c.isspace():
|
|
out.append(c)
|
|
return "".join(out)
|
|
|
|
|
|
def expected_outputs(content):
|
|
"""Each example's Output, in order. 'Output: x' or 'Output' then x on the next line."""
|
|
lines = plain_text(content).split("\n")
|
|
outs = []
|
|
for i, line in enumerate(lines):
|
|
m = re.match(r"\s*Output\s*:?\s*(.*)$", line)
|
|
if not m:
|
|
continue
|
|
value = m.group(1).strip()
|
|
if not value:
|
|
value = next((l.strip() for l in lines[i + 1:] if l.strip()), "")
|
|
outs.append(minify(value))
|
|
return outs
|
|
|
|
|
|
# ----- C++ signatures -----
|
|
|
|
SUPPORTED = {"int", "long", "longlong", "unsigned", "unsignedint", "double", "float",
|
|
"bool", "char", "string", "ListNode*", "TreeNode*"}
|
|
|
|
|
|
def strip_comments(code):
|
|
return re.sub(r"//[^\n]*", "", re.sub(r"/\*.*?\*/", "", code, flags=re.S))
|
|
|
|
|
|
def clean_type(t):
|
|
t = re.sub(r"\bconst\b", "", t).replace("&", "")
|
|
t = re.sub(r"\s+", " ", t).strip()
|
|
return re.sub(r"\s*([<>*,])\s*", r"\1", t)
|
|
|
|
|
|
def supported(t):
|
|
return re.sub(r"vector<|>|\s", "", t) in SUPPORTED
|
|
|
|
|
|
def split_params(text):
|
|
params, depth, cur = [], 0, ""
|
|
for c in text:
|
|
depth += (c == "<") - (c == ">")
|
|
if c == "," and depth == 0:
|
|
params.append(cur)
|
|
cur = ""
|
|
else:
|
|
cur += c
|
|
if cur.strip():
|
|
params.append(cur)
|
|
out = []
|
|
for p in params:
|
|
p = p.split("=")[0].strip()
|
|
m = re.match(r"(.*?)\b(\w+)$", p, re.S)
|
|
out.append((clean_type(m.group(1)), m.group(2)))
|
|
return out
|
|
|
|
|
|
def signature(code, name):
|
|
"""(return type, [(type, name)]) of `name(...)` in the starter code, or None."""
|
|
m = re.search(r"(?:^|[;{}:])\s*([^;{}():]*?)\b" + re.escape(name) + r"\s*\(([^()]*)\)",
|
|
code, re.M)
|
|
if not m:
|
|
return None
|
|
return clean_type(m.group(1)), split_params(m.group(2))
|
|
|
|
|
|
# ----- driver.h -----
|
|
|
|
DRIVER_HEAD = """\
|
|
// driver.h - generated by 'usaco new' from LeetCode's metadata (edit freely).
|
|
// Reads {io}.in in LeetCode's testcase format, cases back to back:
|
|
// {what}
|
|
// and writes one answer per case to {io}.out, formatted the way LeetCode
|
|
// shows its output. Parsing/printing helpers: leetcode.h.
|
|
int main() {{
|
|
freopen("{io}.in", "r", stdin);
|
|
freopen("{io}.out", "w", stdout);
|
|
"""
|
|
|
|
|
|
def function_driver(meta, code, io):
|
|
name = meta["name"]
|
|
sig = signature(code, name)
|
|
if not sig:
|
|
return None, f"no {name}(...) in the C++ starter code"
|
|
ret, params = sig
|
|
n_lines = len(meta.get("params", []))
|
|
if len(params) != n_lines:
|
|
return None, (f"the testcases have {n_lines} line(s) per case but {name}() "
|
|
f"takes {len(params)} argument(s)")
|
|
bad = [t for t, _ in params if not supported(t)] + ([ret] if ret != "void" and not supported(ret) else [])
|
|
if bad:
|
|
return None, f"leetcode.h can't read/print {', '.join(sorted(set(bad)))}"
|
|
|
|
s = DRIVER_HEAD.format(io=io, what="one argument per line")
|
|
s += f" for (vector<string> in; lc::read_case(in, {n_lines});) {{\n"
|
|
for i, (t, n) in enumerate(params):
|
|
s += f" auto {n} = lc::parse<{t}>(in[{i}]);\n"
|
|
call = f"Solution().{name}({', '.join(n for _, n in params)})"
|
|
output = meta.get("output", {})
|
|
idx = output.get("paramindex")
|
|
if idx is not None and output.get("size") == "ret":
|
|
# "return k, and the first k elements of nums" -- LeetCode checks it specially
|
|
arr = params[idx][1]
|
|
s += f" auto k = {call};\n"
|
|
s += f' cout << k << ", {arr} = " << lc::show(lc::prefix({arr}, k)) << \'\\n\';\n'
|
|
elif ret == "void" and idx is not None:
|
|
s += f" {call};\n"
|
|
s += f" cout << lc::show({params[idx][1]}) << '\\n';\n"
|
|
elif ret == "void":
|
|
s += f" {call};\n cout << \"null\\n\";\n"
|
|
else:
|
|
s += f" cout << lc::show({call}) << '\\n';\n"
|
|
s += " }\n}\n"
|
|
return s, None
|
|
|
|
|
|
def design_driver(meta, code, io):
|
|
cls = meta["classname"]
|
|
ctor = signature(code, cls)
|
|
if not ctor:
|
|
return None, f"no {cls}(...) constructor in the C++ starter code"
|
|
ops = [(cls, None, ctor[1])]
|
|
for m in meta.get("methods", []):
|
|
sig = signature(code, m["name"])
|
|
if not sig:
|
|
return None, f"no {m['name']}(...) in the C++ starter code"
|
|
ops.append((m["name"], sig[0], sig[1]))
|
|
bad = sorted({t for _, ret, ps in ops for t in [p[0] for p in ps] + ([ret] if ret and ret != "void" else [])
|
|
if not supported(t)})
|
|
if bad:
|
|
return None, f"leetcode.h can't read/print {', '.join(bad)}"
|
|
|
|
s = DRIVER_HEAD.format(io=io, what="a line of operations, then a line of their arguments")
|
|
s += " for (vector<string> in; lc::read_case(in, 2);) {\n"
|
|
s += " auto ops = lc::parse<vector<string>>(in[0]);\n"
|
|
s += " auto args = lc::parse_val(in[1]).arr;\n"
|
|
s += f" {cls} *obj = nullptr;\n"
|
|
s += " vector<string> out;\n"
|
|
# locals rather than inline lc::as<...>() calls: methods often take
|
|
# vector<int>&, which can't bind a temporary
|
|
s += " for (size_t i = 0; i < ops.size(); i++) {\n"
|
|
s += " auto &a = args.at(i).arr;\n"
|
|
for k, (op, ret, params) in enumerate(ops):
|
|
s += (" if" if k == 0 else " else if") + f' (ops[i] == "{op}") {{\n'
|
|
for j, (t, n) in enumerate(params):
|
|
s += f" auto {n} = lc::as<{t}>(a.at({j}));\n"
|
|
args = ", ".join(n for _, n in params)
|
|
if ret is None:
|
|
s += f" obj = new {cls}({args});\n out.push_back(\"null\");\n"
|
|
elif ret == "void":
|
|
s += f" obj->{op}({args});\n out.push_back(\"null\");\n"
|
|
else:
|
|
s += f" out.push_back(lc::show(obj->{op}({args})));\n"
|
|
s += " }"
|
|
s += ' else {\n lc::fail("unknown operation " + ops[i]);\n }\n'
|
|
s += " }\n cout << lc::list(out) << '\\n';\n }\n}\n"
|
|
return s, None
|
|
|
|
|
|
def stub_driver(io, reason):
|
|
return f"""\
|
|
// driver.h - 'usaco new' couldn't generate a driver for this problem:
|
|
// {reason}
|
|
// Write main() yourself: read {io}.in, call your solution, print to {io}.out.
|
|
// leetcode.h has parse/show helpers for LeetCode's formats.
|
|
int main() {{
|
|
freopen("{io}.in", "r", stdin);
|
|
freopen("{io}.out", "w", stdout);
|
|
cerr << "driver.h: no generated driver ({reason.replace('"', "'")}) -- write main() in driver.h\\n";
|
|
return 1;
|
|
}}
|
|
"""
|
|
|
|
|
|
# ----- main.cpp -----
|
|
|
|
def custom_types(starter):
|
|
"""Types the starter only defines in a comment, other than leetcode.h's.
|
|
|
|
e.g. clone-graph's "/* class Node { ... }; */": LeetCode defines Node itself,
|
|
so main.cpp needs its own copy, but only in LOCAL builds.
|
|
"""
|
|
defs = []
|
|
for block in re.findall(r"/\*(.*?)\*/", starter, re.S):
|
|
lines = block.split("\n")
|
|
if all(re.match(r"\s*(\*|$)", l) for l in lines[1:]): # " * struct ..." style
|
|
lines = [re.sub(r"^\s*\* ?", "", l) for l in lines]
|
|
text = "\n".join(lines)
|
|
m = re.search(r"^(class|struct)\s+(\w+)", text, re.M)
|
|
if m and m.group(2) not in ("ListNode", "TreeNode"):
|
|
defs.append(text[m.start():].strip())
|
|
return defs
|
|
|
|
|
|
def main_cpp(root, starter):
|
|
"""template.cpp up to its main(), with leetcode.h added, then the starter code."""
|
|
tpl = (root / "template.cpp").read_text()
|
|
head = tpl.split("\nint main() {", 1)[0].rstrip() + "\n"
|
|
head = head.replace('#include "debugging.h"\n',
|
|
'#include "debugging.h"\n#include "leetcode.h" // ListNode, TreeNode\n', 1)
|
|
for d in custom_types(starter):
|
|
head += f"\n#ifdef LOCAL // LeetCode defines this itself\n{d}\n#endif\n"
|
|
return (f"{head}\n{starter.rstrip()}\n\n"
|
|
"#ifdef LOCAL // runs the examples; see driver.h\n"
|
|
'#include "driver.h"\n'
|
|
"#endif\n")
|
|
|
|
|
|
def fetch(slug):
|
|
q = graphql(QUESTION, {"s": slug})["question"]
|
|
if q is None:
|
|
die(f"LeetCode has no problem '{slug}'")
|
|
if not q.get("content"):
|
|
die(f"LeetCode returned no statement for '{slug}' (a premium problem?)")
|
|
return q
|
|
|
|
|
|
def cpp_starter(q):
|
|
starter = next((s["code"] for s in q["codeSnippets"] or [] if s["langSlug"] == "cpp"), None)
|
|
if starter is None:
|
|
die("this problem has no C++ starter code")
|
|
return starter
|
|
|
|
|
|
def main():
|
|
if len(sys.argv) < 3:
|
|
die(__doc__.strip().split("\n")[2])
|
|
root = Path(sys.argv[1])
|
|
|
|
if "--main-only" in sys.argv[3:]:
|
|
d = Path(sys.argv[2])
|
|
url = (d / ".url").read_text().strip() if (d / ".url").exists() else ""
|
|
q = fetch(slug_of(url))
|
|
(d / "main.cpp").write_text(main_cpp(root, cpp_starter(q)))
|
|
print(d.name)
|
|
return
|
|
|
|
slug = slug_of(sys.argv[2])
|
|
for status in ("solving", "solved", "skipped"):
|
|
if (root / status / slug).exists():
|
|
die(f"'{slug}' already exists ({status}/{slug})")
|
|
q = fetch(slug)
|
|
starter = cpp_starter(q)
|
|
meta = json.loads(q["metaData"])
|
|
io = slug
|
|
|
|
code = strip_comments(starter)
|
|
if meta.get("systemdesign") or "classname" in meta:
|
|
driver, why = design_driver(meta, code, io)
|
|
else:
|
|
driver, why = function_driver(meta, code, io)
|
|
if driver is None:
|
|
driver = stub_driver(io, why)
|
|
|
|
cases = [c.strip() + "\n" for c in q["exampleTestcaseList"] or []]
|
|
outs = expected_outputs(q["content"])
|
|
if meta.get("output", {}).get("size") == "ret":
|
|
outs, out_note = [], "the answer is checked specially on LeetCode, so no expected outputs"
|
|
elif len(outs) != len(cases):
|
|
out_note = f"found {len(outs)} Output(s) for {len(cases)} example(s), so no expected outputs"
|
|
outs = []
|
|
else:
|
|
out_note = None
|
|
|
|
d = root / "solving" / slug
|
|
(d / "tests").mkdir(parents=True)
|
|
title = f"{q['questionFrontendId']}. {q['title']}"
|
|
(d / "problem.md").write_text(f"# {title}\n\n{to_markdown(q['content'])}\n")
|
|
(d / ".url").write_text(f"https://leetcode.com/problems/{slug}/\n")
|
|
(d / "main.cpp").write_text(main_cpp(root, starter))
|
|
(d / "driver.h").write_text(driver)
|
|
(d / f"{io}.in").write_text("".join(cases))
|
|
for n, case in enumerate(cases, 1):
|
|
(d / "tests" / f"{n}.in").write_text(case)
|
|
if outs:
|
|
(d / "tests" / f"{n}.out").write_text(outs[n - 1] + "\n")
|
|
if not cases:
|
|
(d / "tests").rmdir()
|
|
|
|
print(f"Fetched {title}: {len(cases)} example(s)"
|
|
+ (f" with expected outputs" if outs else ""), file=sys.stderr)
|
|
if out_note:
|
|
print(f"note: {out_note}", file=sys.stderr)
|
|
if why:
|
|
print(f"note: no driver generated ({why}); write main() in driver.h", file=sys.stderr)
|
|
print(slug)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|