Skip to content

Commit abb9d57

Browse files
committed
random problem selection
1 parent 8cb7bd3 commit abb9d57

File tree

5 files changed

+57
-62
lines changed

5 files changed

+57
-62
lines changed

leetcode/main.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,10 +52,12 @@ def main():
5252

5353
problem_parser = subparsers.add_parser('problem', help="Display problem")
5454
problem_parser.set_defaults(func=ProblemInfo)
55-
problem_parser.add_argument('id', type=positive_integer, help='Problem ID of the problem')
55+
problem_parser.add_argument('-r', '--random', action='store_true', help='Fetch a random problem.')
56+
problem_parser.add_argument('id', type=positive_integer, help='Problem ID of the problem', default=0, nargs='?')
5657
problem_parser.add_argument('-b', '--browser', action='store_true', help='Open the page in browser.')
5758
problem_parser.add_argument('-f', '--file', action='store_true', help='Create a file with the problem content.')
5859

60+
5961
today_problem_parser = subparsers.add_parser('today', help="Display today's problem.")
6062
today_problem_parser.set_defaults(func=QuestionOfToday)
6163

leetcode/models/graphql_problemset_question_list.py

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,11 @@ def from_dict(cls, data):
3333
class TotalCount(JSONWizard):
3434
total: int
3535
class ProblemTotalCount(QueryTemplate):
36-
def __init__(self):
36+
def __init__(self, filters={}):
3737
super().__init__()
3838
self.graphql_query = None
3939
self.result = None
40-
self.params = {'categorySlug': "", 'skip': 0, 'limit': 10, 'filters': {}}
40+
self.params = {'categorySlug': "", 'skip': 0, 'limit': 10, 'filters': filters}
4141

4242
self.execute()
4343

@@ -50,14 +50,16 @@ def __call__(self, *args: Any, **kwds: Any) -> Any:
5050

5151

5252
class ProblemsetQuestionList(QueryTemplate):
53-
def __init__(self):
53+
def __init__(self, filters={}, limit=None, skip=0):
5454
super().__init__()
5555
# Instance specific variables
5656
self.page : int = 1
5757
self.max_page : int = 0
58-
self.limit = self.config.user_config.get('question_list_limit')
58+
self.filters = filters
59+
self.limit = limit or self.config.user_config.get('question_list_limit')
60+
self.skip = skip
5961

60-
self.params = {'categorySlug': "", 'skip': 0, 'limit': self.limit, 'filters': {}}
62+
self.params = {'categorySlug': "", 'skip':self.skip, 'limit': self.limit, 'filters': self.filters}
6163
self.graphql_query = None
6264
self.result = None
6365

@@ -94,11 +96,9 @@ def execute(self, args):
9496
def validate_page(self):
9597
""" Method to validate the page number. If number is too large,
9698
set the page number to the last page."""
97-
9899
count = ProblemTotalCount().__call__()
99-
if self.page > -(-count // self.limit): # ceil(total / limit)
100-
self.page = -(-count // self.limit)
101-
self.params['skip'] = self.limit * self.page - self.limit # update the skip value
100+
self.page = min(self.page, -(-count // self.limit))
101+
self.params['skip'] = self.limit * self.page - self.limit # update the skip value
102102

103103
def show(self):
104104
displayed : int = self.limit * self.page if self.limit * self.page < self.result.total else self.result.total
@@ -113,4 +113,10 @@ def show(self):
113113
table.add_column('Difficulty')
114114
for item in self.result.questions:
115115
table.add_row(item.questionId, item.title, item.status, item.difficulty)
116-
print(table)
116+
print(table)
117+
118+
def get_data(self):
119+
self.graphql_query = GraphQLQuery(self.query, self.params)
120+
self.result = self.leet_API.post_query(self.graphql_query)
121+
122+
return self.result['data']

leetcode/models/problem_by_id_slug.py

Lines changed: 38 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from leetcode.models.graphql_get_question_detail import GetQuestionDetail
55
from leetcode.models.graphql_question_content import QuestionContent
66
from leetcode.models.graphql_question_info_table import QuestionInfoTable
7+
from leetcode.models.graphql_problemset_question_list import ProblemTotalCount, ProblemsetQuestionList
78

89

910
class ProblemInfo(QueryTemplate):
@@ -53,22 +54,42 @@ def parse_args(self, args):
5354
self.fileFlag = True
5455

5556
def execute(self, args):
56-
self.parse_args(args)
57-
try:
58-
with Loader('Fetching problem info...', ''):
59-
self.result = self.leet_api.get_request(self.API_URL)
60-
if getattr(args, 'id'):
61-
for item in self.result.get('stat_status_pairs', []):
62-
if item['stat'].get('question_id') == args.id:
63-
self.title_slug = item['stat'].get('question__title_slug', '')
64-
break
65-
if not self.title_slug:
66-
raise ValueError("Invalid ID has been provided. Please try again.")
67-
self.show()
68-
except Exception as e:
69-
console.print(f"{e.__class__.__name__}: {e}", style=ALERT)
70-
if self.fileFlag:
71-
self.create_submission_file()
57+
self.parse_args(args)
58+
if getattr(args, 'random'):
59+
total = ProblemTotalCount({'status': 'NOT_STARTED'}).__call__()
60+
61+
from random import randint
62+
with Loader('Selecting random problem...', ''):
63+
choosen_number = randint(1, total)
64+
while True:
65+
list_instance = ProblemsetQuestionList({'status': 'NOT_STARTED'}, limit=1, skip=choosen_number - 1)
66+
problem = list_instance.get_data()['problemsetQuestionList']['questions'][0]
67+
if not problem['paidOnly']:
68+
break
69+
choosen_number = randint(1, total)
70+
71+
with Loader('Fetching problem contents...', ''):
72+
question_info_table = QuestionInfoTable(problem['titleSlug'])
73+
question_content = QuestionContent(problem['titleSlug'])
74+
console.print(question_info_table)
75+
console.print(question_content)
76+
77+
else:
78+
try:
79+
with Loader('Fetching problem info...', ''):
80+
self.result = self.leet_api.get_request(self.API_URL)
81+
if getattr(args, 'id'):
82+
for item in self.result.get('stat_status_pairs', []):
83+
if item['stat'].get('question_id') == args.id:
84+
self.title_slug = item['stat'].get('question__title_slug', '')
85+
break
86+
if not self.title_slug:
87+
raise ValueError("Invalid ID has been provided. Please try again.")
88+
self.show()
89+
except Exception as e:
90+
console.print(f"{e.__class__.__name__}: {e}", style=ALERT)
91+
if self.fileFlag:
92+
self.create_submission_file()
7293

7394
def create_submission_file(self):
7495
question = GetQuestionDetail(self.title_slug)
@@ -88,4 +109,4 @@ def show(self):
88109
question_info_table = QuestionInfoTable(self.title_slug)
89110
console.print(question_info_table)
90111
question_content = QuestionContent(self.title_slug)
91-
console.print(question_content)
112+
console.print(question_content)

smallest-subsequence-of-distinct-characters.1059514138.py

Lines changed: 0 additions & 24 deletions
This file was deleted.

two-sum.1008758093.py

Lines changed: 0 additions & 10 deletions
This file was deleted.

0 commit comments

Comments
 (0)