Skip to content

Commit d573d81

Browse files
committed
Use new APIs
1 parent 341a7b3 commit d573d81

File tree

6 files changed

+33
-38
lines changed

6 files changed

+33
-38
lines changed

.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# Created by .ignore support plugin (hsz.mobi)
22
/contest_problems.pkl
3+
/contest_cpp/
4+
/contest_python/
35

46
### Python template
57
# Byte-compiled / optimized / DLL files

lchelper/common.py

+15-7
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from dataclasses import dataclass
12
from typing import Any, Dict, List, NamedTuple, Optional, Tuple
23

34
__all__ = [
@@ -11,7 +12,8 @@
1112
]
1213

1314

14-
class User(NamedTuple):
15+
@dataclass
16+
class User:
1517
username: str
1618
site: str # "leetcode" or "leetcode-cn"
1719

@@ -21,7 +23,8 @@ def __repr__(self):
2123
return f"{self.username} ({self.site})"
2224

2325

24-
class Problem(NamedTuple):
26+
@dataclass
27+
class Problem:
2528
"""Raw description of the problem crawled from the web page."""
2629

2730
url: str
@@ -32,29 +35,33 @@ class Problem(NamedTuple):
3235
code: List[str] # template code, in lines
3336

3437

35-
class FunctionSignature(NamedTuple):
38+
@dataclass
39+
class FunctionSignature:
3640
"""Signature of a function."""
3741

3842
name: str
3943
arguments: List[Tuple[str, str]] # list of (type, name)
4044
return_type: str
4145

4246

43-
class Example(NamedTuple):
47+
@dataclass
48+
class Example:
4449
"""An example test case, consisting of an input--output pair."""
4550

4651
input: Dict[str, Any]
4752
output: Any
4853

4954

50-
class ProblemSignature(NamedTuple):
55+
@dataclass
56+
class ProblemSignature:
5157
"""Signature of a problem, including the function signature and test cases."""
5258

5359
function: FunctionSignature
5460
examples: List[Example]
5561

5662

57-
class Interaction(NamedTuple):
63+
@dataclass
64+
class Interaction:
5865
"""
5966
An "interaction" in interactive problems. An example test case for interactive
6067
problems consist of multiple "interactions", where each interaction calls a specific
@@ -66,7 +73,8 @@ class Interaction(NamedTuple):
6673
output: Optional[Any]
6774

6875

69-
class InteractiveProblemSignature(NamedTuple):
76+
@dataclass
77+
class InteractiveProblemSignature:
7078
"""Signature of an interactive problem."""
7179

7280
class_name: str

lchelper/crawler.py

+9-9
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ def update_cookie(username: str, site: str) -> None:
9393
)
9494
print("Login page loaded. Please enter your password in the browser window.")
9595

96-
elem = browser.find_element_by_css_selector('input[name="login"]')
96+
elem = browser.find_element(By.CSS_SELECTOR, 'input[name="login"]')
9797
elem.clear()
9898
elem.send_keys(username)
9999

@@ -167,8 +167,8 @@ def get_problems(contest_url: str, site: str, cookie_path: str) -> List[Problem]
167167
print(f"Cookie '{cookie_path}' might have expired. Please try logging in again")
168168
exit(1)
169169

170-
elem = browser.find_element_by_css_selector("ul.contest-question-list")
171-
links = elem.find_elements_by_tag_name("a")
170+
elem = browser.find_element(By.CSS_SELECTOR, "ul.contest-question-list")
171+
links = elem.find_elements(By.TAG_NAME, "a")
172172
problem_paths = [(link.get_attribute("href"), link.text) for link in links]
173173
log(f"Found problems: {[name for _, name in problem_paths]!r}")
174174

@@ -179,27 +179,27 @@ def get_problems(contest_url: str, site: str, cookie_path: str) -> List[Problem]
179179
# Page during contest; editor located below statement.
180180
statement_css_selector = "div.question-content"
181181
code_css_selector = "pre.CodeMirror-line"
182-
statement = browser.find_element_by_css_selector(
183-
statement_css_selector
182+
statement = browser.find_element(
183+
By.CSS_SELECTOR, statement_css_selector
184184
).text
185185
except (TimeoutException, NoSuchElementException):
186186
# Page after contest; statement and editor in vertically split panes.
187187
statement_css_selector = (
188188
"div[data-key='description-content'] div.content__1Y2H"
189189
)
190190
code_css_selector = "div.monaco-scrollable-element div.view-line"
191-
statement = browser.find_element_by_css_selector(
192-
statement_css_selector
191+
statement = browser.find_element(
192+
By.CSS_SELECTOR, statement_css_selector
193193
).text
194194
examples = [
195195
elem.text
196-
for elem in browser.find_elements_by_css_selector("pre:not([class])")
196+
for elem in browser.find_elements(By.CSS_SELECTOR, "pre:not([class])")
197197
if elem.text
198198
]
199199
# TODO: Should make sure C++ is selected!
200200
code = [
201201
elem.text
202-
for elem in browser.find_elements_by_css_selector(code_css_selector)
202+
for elem in browser.find_elements(By.CSS_SELECTOR, code_css_selector)
203203
]
204204
problem = Problem(problem_url, problem_name, statement, examples, code)
205205
parsed_problems.append(problem)

lchelper/logging.py

-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
import time
2-
31
from termcolor import colored
42

53
__all__ = [

lchelper/utils.py

+4-16
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,12 @@
11
import sys
2-
from typing import Any, Dict, NamedTuple, Optional, Type, TypeVar
2+
from typing import Optional
33

44
__all__ = [
5-
"to_dict",
6-
"from_dict",
75
"remove_affix",
86
"register_excepthook",
97
]
108

119

12-
def to_dict(nm_tpl: NamedTuple) -> Dict[str, Any]:
13-
return nm_tpl._asdict()
14-
15-
16-
TupleType = TypeVar("TupleType", bound=NamedTuple)
17-
18-
19-
def from_dict(tpl_class: Type[TupleType], d: Dict[str, Any]) -> TupleType:
20-
assert all(field in d for field in tpl_class._fields)
21-
return tpl_class(**d)
22-
23-
2410
def remove_affix(
2511
s: str, prefix: Optional[str] = None, suffix: Optional[str] = None
2612
) -> str:
@@ -42,5 +28,7 @@ def excepthook(type, value, traceback):
4228
# enter IPython debugger on exception
4329
from IPython.core import ultratb
4430

45-
ipython_hook = ultratb.FormattedTB(mode="Context", color_scheme="Linux", call_pdb=1)
31+
ipython_hook = ultratb.FormattedTB(
32+
mode="Context", color_scheme="Linux", call_pdb=True
33+
)
4634
sys.excepthook = excepthook

main.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import argparse
2+
import dataclasses
23
import os
34
import pickle
45
import sys
@@ -183,13 +184,11 @@ def main():
183184

184185
problems = lchelper.get_problems(url, user.site, cookie_path)
185186

186-
info[site, contest_name] = [lchelper.utils.to_dict(p) for p in problems]
187+
info[site, contest_name] = [dataclasses.asdict(p) for p in problems]
187188
with open(CACHE_FILE, "wb") as f:
188189
pickle.dump(info, f)
189190
else:
190-
problems = [
191-
lchelper.utils.from_dict(lchelper.Problem, p) for p in cached_problems
192-
]
191+
problems = [lchelper.Problem(**p) for p in cached_problems]
193192

194193
for lang in args.lang:
195194
codegen = lchelper.create_codegen(lang)

0 commit comments

Comments
 (0)