Package: python-leetcode
Leetcode API implementationThis repo contains a python client to access all known so far methods of Leetcode API.The code is autogenerated by swagger. Swagger reference can be found here:https://github.com/prius/leetcode-swaggerPyPi package link:https://pypi.org/project/python-leetcode/Minimal working exampleFirst set up a virtualenvvirtualenv-ppython3leetcode
.leetcode/bin/activate
pip3installpython-leetcodeThen in python shell initialize the client (if you're using chrome, cookies can be found herechrome://settings/cookies/detail?site=leetcode.com)importleetcode# Get the next two values from your browser cookiesleetcode_session="yyy"csrf_token="xxx"# Experimental: Or CSRF token can be obtained automaticallyimportleetcode.authcsrf_token=leetcode.auth.get_csrf_cookie(leetcode_session)configuration=leetcode.Configuration()configuration.api_key["x-csrftoken"]=csrf_tokenconfiguration.api_key["csrftoken"]=csrf_tokenconfiguration.api_key["LEETCODE_SESSION"]=leetcode_sessionconfiguration.api_key["Referer"]="https://leetcode.com"configuration.debug=Falseapi_instance=leetcode.DefaultApi(leetcode.ApiClient(configuration))Now once the client is initilized, you can start performing actual queriesgraphql_request=leetcode.GraphqlQuery(query="""{user {usernameisCurrentUserPremium}}""",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 exampleNow 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:Trueifpair.status=="ac"elseFalseforpairinapi_response.stat_status_pairs}Now for each problem we want to get its tagsimporttimefromcollectionsimportCountertopic_to_accepted=Counter()topic_to_total=Counter()# Take only the first 10 for test purposesforsluginlist(slug_to_solved_status.keys())[:10]:time.sleep(1)# Leetcode has a rate limitergraphql_request=leetcode.GraphqlQuery(query="""query getQuestionDetail($titleSlug: String!) {question(titleSlug: $titleSlug) {topicTags {nameslug}}}""",variables=leetcode.GraphqlQueryVariables(title_slug=slug),operation_name="getQuestionDetail",)api_response=api_instance.graphql_post(body=graphql_request)fortopicin(tag.slugfortaginapi_response.data.question.topic_tags):topic_to_accepted[topic]+=int(slug_to_solved_status[slug])topic_to_total[topic]+=1print(list(sorted(((topic,accepted/topic_to_total[topic])fortopic,acceptedintopic_to_accepted.items()),key=lambdax: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 tohttps://leetcode.com/tag/memoization/and choose a new memoization problem. Or use python to automate the process.Example services using this libraryAnki cards generatorhttps://github.com/prius/leetcode-ankiLeetcode helper websitehttps://github.com/prius/grind-helperAdditional infoYou can find other examples of usage inexample.pyAutogenerated by swagger documentation can be foundhere.