Skip to content

Commit d2528c2

Browse files
committed
classes restructurization
1 parent 3d94468 commit d2528c2

File tree

8 files changed

+386
-110
lines changed

8 files changed

+386
-110
lines changed

leetcode/main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ def main():
8080

8181
if hasattr(args, 'func'):
8282
command_instance = args.func()
83-
command_instance.execute(args)
83+
command_instance._execute(args) # call the private method __execute
8484
else:
8585
print("Unknown command. Use 'leet --help' for available commands.")
8686

Lines changed: 84 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,114 @@
11
from leetcode.models import *
22

33
class GetQuestionDetail(QueryTemplate):
4+
""" A class to represent a LeetCode problem.
5+
6+
Args:
7+
title_slug (str): The title slug of the problem.
8+
"""
49
def __init__(self, title_slug: str):
510
super().__init__()
611
# Instance-specific variables
712
self._title_slug = title_slug
13+
self._data = None
14+
self._params = {'titleSlug': title_slug}
15+
self._data_fetched: bool = False
816

9-
self.graphql_query = None
10-
self.result = None
11-
self.params = {'titleSlug': title_slug}
12-
13-
# Initialize variables to store query data
14-
self._question_data = None
15-
self.execute()
17+
self.fetch_data()
1618

17-
def execute(self):
18-
self.graphql_query = GraphQLQuery(self.query, self.params)
19-
self.result = self.leet_API.post_query(self.graphql_query)
20-
# Store the entire question data
21-
self._question_data = self.result.get('data', {}).get('question', {})
19+
def fetch_data(self, title_slug: str = None) -> Dict:
20+
""" Fetches the data for the problem.
21+
22+
Args:
23+
parameters (dict, optional): Parameters to pass to the query. Defaults to None.
24+
25+
Returns:
26+
Dict: The data for the problem.
27+
"""
28+
try:
29+
with Loader('Fetching question details...', ''):
30+
if title_slug is None:
31+
parameters = self.params
32+
elif title_slug != self.title_slug:
33+
self.title_slug = title_slug
34+
self.params = {'titleSlug': title_slug}
35+
parameters = self.params
36+
if self.data_fetched:
37+
return self._data
2238

39+
graphql_query = GraphQLQuery(self.query, parameters)
40+
response = self.leet_API.post_query(graphql_query)
41+
if 'errors' in response:
42+
raise Exception(response['errors'][0]['message'])
43+
self.data = response['data']['question']
44+
self.data_fetched = True
45+
self.params = parameters
46+
return self.data
47+
except Exception as e:
48+
console.print(f"{e.__class__.__name__}: {e}", style=ALERT)
49+
sys.exit(1)
50+
51+
@property
52+
def data(self):
53+
return self._data
54+
55+
@data.setter
56+
def data(self, data: dict):
57+
if data is None:
58+
raise ValueError(f"Data for question with title slug '{self.title_slug}' is None.")
59+
self._data = data
60+
61+
@property
62+
def params(self):
63+
return self._params
64+
65+
@params.setter
66+
def params(self, params: dict):
67+
self._params = params
68+
2369
@property
2470
def title_slug(self):
2571
return self._title_slug
72+
73+
@title_slug.setter
74+
def title_slug(self, title_slug: str):
75+
self._title_slug = title_slug
76+
self._data_fetched = False
77+
self.params = {'titleSlug': title_slug}
78+
79+
@property
80+
def data_fetched(self):
81+
return self._data_fetched
82+
83+
@data_fetched.setter
84+
def data_fetched(self, data_fetched: bool):
85+
self._data_fetched = data_fetched
2686

2787
@property
2888
def question_id(self):
29-
return self._question_data.get('questionId')
89+
return self._data.get('questionId')
3090

3191
@property
3292
def question_frontend_id(self):
33-
return self._question_data.get('questionFrontendId')
93+
return self._data.get('questionFrontendId')
3494

3595
@property
3696
def title(self):
37-
return self._question_data.get('title')
97+
return self._data.get('title')
3898

3999
@property
40100
def content(self):
41-
return self._question_data.get('content')
101+
return self._data.get('content')
42102

43103
@property
44104
def sample_test_case(self):
45-
return self._question_data.get('sampleTestCase')
105+
return self._data.get('sampleTestCase')
46106

47107
@property
48-
def code_snippet(self, lang: str = 'python3'):
49-
return list(filter(lambda x: x['langSlug'] == lang, self._question_data.get('codeSnippets')))[0].get('code')
108+
def code_snippet(self, lang='python3'):
109+
return next((x['code'] for x in self._data.get('codeSnippets') if x['langSlug'] == lang), None)
110+
111+
if __name__ == "__main__":
112+
details = GetQuestionDetail('two-shrtum')
113+
print(details.code_snippet)
114+
Lines changed: 116 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,127 @@
11
from leetcode.models import *
22

33
class QuestionContent(QueryTemplate):
4-
def __init__(self, titleSlug):
4+
""" A class to represent a LeetCode problem content.
5+
6+
Args:
7+
title_slug (str): The title slug of the problem. """
8+
9+
def __init__(self, title_slug):
510
super().__init__()
6-
self.params = {'titleSlug': titleSlug}
7-
self.result = None
11+
# Instance-specific variables
12+
self._title_slug = title_slug
13+
self._data = None
14+
self._params = {'titleSlug': title_slug}
15+
self._data_fetched: bool = False
16+
17+
self.question_panels: List[rich.panel.Panel] = []
18+
self.fetch_data(self.title_slug)
819

9-
self.execute()
10-
self.question_panels = LeetQuestionToSections(self.result)
20+
def fetch_data(self, title_slug: str = None) -> Dict:
21+
""" Fetches the content data for the problem.
1122
12-
def execute(self):
13-
self.graphql_query = GraphQLQuery(self.query, self.params)
14-
self.result = self.leet_API.post_query(self.graphql_query)
15-
if 'errors' in self.result:
16-
console.print("Cannot find the question with specified title slug. Please try again.", style=ALERT)
23+
Args:
24+
parameters (dict, optional): Parameters to pass to the query. Defaults to None.
25+
26+
Returns:
27+
Dict: The content data for the problem.
28+
"""
29+
try:
30+
with Loader('Fetching question details...', ''):
31+
parameters = self.params
32+
if title_slug is None:
33+
parameters = self.params
34+
elif title_slug != self.title_slug:
35+
self.title_slug = title_slug
36+
self.params = {'titleSlug': title_slug}
37+
parameters = self.params
38+
if self.data_fetched:
39+
return self._data
40+
41+
graphql_query = GraphQLQuery(self.query, parameters)
42+
response = self.leet_API.post_query(graphql_query)
43+
if response['data']['question'] is None:
44+
raise Exception('There is no question with title slug: ' + title_slug)
45+
self.data = response['data']['question']['content']
46+
self.data_fetched = True
47+
self.params = parameters
48+
return self.data
49+
except Exception as e:
50+
console.print(f"{e.__class__.__name__}: {e}", style=ALERT)
1751
sys.exit(1)
18-
else:
19-
self.result = self.result['data']['question']['content']
2052

2153
def show(self):
22-
for x in self.question_panels:
23-
console.print(x)
54+
""" Displays the question panels for the current LeetCode question.
55+
56+
If the data has not been fetched yet, an exception is raised.
57+
"""
58+
if self.data_fetched:
59+
self.question_panels = LeetQuestionToSections(self.data)
60+
for x in self.question_panels:
61+
console.print(x)
62+
else:
63+
raise Exception("Data is not fetched yet.")
2464

2565
def __rich_console__(self, console: Console, options):
26-
for x in self.question_panels:
27-
yield x
66+
""" Renders the question content in a rich console.
67+
68+
If the data has been fetched, the question panels are generated using the LeetQuestionToSections function and yielded.
69+
If the data has not been fetched, an exception is raised.
70+
71+
Args:
72+
console (Console): The console to render the content in.
73+
options: Additional options for rendering the content.
74+
75+
Raises:
76+
Exception: If the data has not been fetched yet.
77+
"""
78+
if self.data_fetched:
79+
self.question_panels = LeetQuestionToSections(self.data)
80+
for x in self.question_panels:
81+
yield x
82+
else:
83+
# raise exception that data is not fetched
84+
raise Exception("Data is not fetched yet.")
85+
86+
@property
87+
def data(self):
88+
return self._data
89+
90+
@data.setter
91+
def data(self, data: dict):
92+
if data is None:
93+
raise ValueError(f"Data for question with title slug '{self.title_slug}' is None.")
94+
self._data = data
95+
96+
@property
97+
def params(self):
98+
return self._params
99+
100+
@params.setter
101+
def params(self, params: dict):
102+
self._params = params
103+
104+
@property
105+
def title_slug(self):
106+
return self._title_slug
107+
108+
@title_slug.setter
109+
def title_slug(self, title_slug: str):
110+
self._title_slug = title_slug
111+
self._data_fetched = False
112+
self.params = {'titleSlug': title_slug}
113+
114+
@property
115+
def data_fetched(self):
116+
return self._data_fetched
117+
118+
@data_fetched.setter
119+
def data_fetched(self, data_fetched: bool):
120+
self._data_fetched = data_fetched
121+
122+
123+
if __name__ == '__main__':
124+
content = QuestionContent('two-sumfsdf')
125+
print(content)
126+
content.fetch_data('add-two-integers')
127+
print(content)

0 commit comments

Comments
 (0)