Leetcode API
Project description
Leetcode API implementation.
This implements methods that are available publicly for leetcode. There is already an implementation of them in form of CLI [1], but it has a list of disadvantages.
-
It is written in JS
-
Even for JS in order to reuse it you have to invoke it via CLI
-
It is not supported very well, so authentication doesn't work anymore
So I have decided to create my own implementation and here is it.
Using the swagger file you'll be able to generate the code for any language you like and start using leetcode API directly from your code.
Just keep in mind that swagger doesn't really support cookie auth,
which is needed in order to use LC API. If you use python you can
just use the generated code from this repo. Otherwise you'll have to
implement something like fix_cookies.patch
for your target language.
Minimal working example
First set up a virtualenv
virtualenv -p python3 leetcode
. leetcode/bin/activate
pip3 install python-leetcode
Then in python shell initialize the client
import leetcode
# Get the next two values from your browser cookies
csrf_token = "xxx"
leetcode_session = "yyy"
configuration = leetcode.Configuration()
configuration.api_key["x-csrftoken"] = csrf_token
configuration.api_key["csrftoken"] = csrf_token
configuration.api_key["LEETCODE_SESSION"] = leetcode_session
configuration.api_key["Referer"] = "https://leetcode.com"
configuration.debug = False
api_instance = leetcode.DefaultApi(leetcode.ApiClient(configuration))
Now once the client is initilized, you can start performing actual queries
graphql_request = leetcode.GraphqlQuery(
query="""
{
user {
username
isCurrentUserPremium
}
}
""",
variables=leetcode.GraphqlQueryVariables(),
)
print(api_instance.graphql_post(body=graphql_request))
You should get something like that in the response
{'data': {'question': None,
'user': {'is_current_user_premium': True, 'username': 'omgitspavel'}}}
This confirms you've set up auth correctly.
Advanced example
Now let's try to do something more complicated. For example calculate the percentage of the problems we've solved by topic.
For that we have to acquire the list of all the problems we solved.
api_response = api_instance.api_problems_topic_get(topic="algorithms")
slug_to_solved_status = {
pair.stat.question__title_slug: True if pair.status == "ac" else False
for pair in api_response.stat_status_pairs
}
Now for each problem we want to get its tags
import time
from collections import Counter
topic_to_accepted = Counter()
topic_to_total = Counter()
# Take only the first 10 for test purposes
for slug in list(slug_to_solved_status.keys())[:10]:
time.sleep(1) # Leetcode has a rate limiter
graphql_request = leetcode.GraphqlQuery(
query="""
query getQuestionDetail($titleSlug: String!) {
question(titleSlug: $titleSlug) {
topicTags {
name
slug
}
}
}
""",
variables=leetcode.GraphqlQueryVariables(title_slug=slug),
operation_name="getQuestionDetail",
)
api_response = api_instance.graphql_post(body=graphql_request)
for topic in (tag.slug for tag in api_response.data.question.topic_tags):
topic_to_accepted[topic] += int(slug_to_solved_status[slug])
topic_to_total[topic] += 1
print(
list(
sorted(
((topic, accepted / topic_to_total[topic]) for topic, accepted in topic_to_accepted.items()),
key=lambda x: x[1]
)
)
)
The output will look like this:
[('memoization', 0.0),
('number-theory', 0.0),
('binary-search-tree', 0.0),
('quickselect', 0.0),
('recursion', 0.0),
('suffix-array', 0.0),
('topological-sort', 0.0),
('shortest-path', 0.0),
('trie', 0.0),
('geometry', 0.0),
('brainteaser', 0.0),
('combinatorics', 0.0),
('line-sweep', 0.0),
...
('union-find', 0.3076923076923077),
('linked-list', 0.3333333333333333),
('string-matching', 0.3333333333333333),
('segment-tree', 0.4),
('data-stream', 0.5),
('strongly-connected-component', 0.5),
('minimum-spanning-tree', 0.6666666666666666),
('merge-sort', 1.0),
('doubly-linked-list', 1.0)]
So it is clearly visible which topics we should focus on in our preparation. In this case memoization topic is one of the targets for improvement, so I can go to https://leetcode.com/tag/memoization/ and choose a new memoization problem. Or use python to automate the process.
You can find other examples of usage in example.py
Autogenerated by swagger documentation can be found here.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
File details
Details for the file python-leetcode-1.0.1.tar.gz
.
File metadata
- Download URL: python-leetcode-1.0.1.tar.gz
- Upload date:
- Size: 31.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.6.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 8ea4ee2d8bcc89b0b88bedf0540ec0ddcba6e3171b979582a17d99f40d40b7a8 |
|
MD5 | 9c6c6ce40ad26487773986c3c0faae38 |
|
BLAKE2b-256 | 4727d4f32a843ec8f4d2232f785095eb395008d468a618d8f9b6b1bd3ad4a84d |