LeetCode幾乎成了如今每一個人找工做前都要刷的"新手村"的怪,每個找工做的人面試以前都要都會去刷一刷。閒話很少說,先看看大佬們都是怎麼評價LeetCodejavascript
雖然面試官也不會看你github上leetcode的repo,可是若是你有這麼一個東西仍是極好的,不少大佬都會去刷這個東西,放在github上面,固然新手也會這麼作。咱們就會發現,大佬們的README超級好看,方便本身往後查找,可是新手的命名就比較雜亂無章,一點也不規範,本身找起來很是費勁。我本身就是這麼一個狀況,因此我決定重構一下這個目錄結構,生成一個好看一點的。java
咱們先看一下生成的效果吧!更詳細具體效果請查看這裏python
在github上建立一個倉庫,好比叫leetcode或者像個人同樣叫algorithms_and_oj。而後從github中git clone下來。c++
而後,安裝項目前置須要的庫:git
pip install requests
複製代碼
首先須要配置咱們的路徑 (如下路徑均按照我項目來配置,須要按照本身要求修改)github
class Config:
""" some config, such as your github page 這裏須要配置你本身的項目地址 1. 本地倉庫的的路徑 2. github中的倉庫leetcode解法的路徑 """
local_path = '/home/yuan/PycharmProjects/algorithms_and_oj'
# solution of leetcode
github_leetcode_url = 'https://github.com/hey-bruce/algorithms_and_oj/blob/master/leetcode-algorithms/'
# solution of pat, 暫時還沒用上
github_pat_url = 'https://github.com/hey-bruce/algorithms_and_oj/blob/master/pat-algorithms/'
leetcode_url = 'https://leetcode.com/problems/'
複製代碼
咱們須要哪些信息,每一個問題的ID,title, url,難度,已經使用什麼語言解決等,因此咱們很天然的構造一個Question類面試
class Question:
""" this class used to store the inform of every question """
def __init__(self, id_, name, url, lock, difficulty):
self.id_ = id_
self.title = name
# the problem description url 問題描述頁
self.url = url
self.lock = lock # boolean,鎖住了表示須要購買
self.difficulty = difficulty
# the solution url
self.python = ''
self.java = ''
self.javascript = ''
self.c_plus_plus = ''
def __repr__(self):
""" 沒啥用,我爲了調試方便寫的 :return: """
return str(self.id_) + ' ' + str(self.title) + ' ' + str(self.url)
複製代碼
接下來,咱們就要從LeetCode上獲取問題,在在google一查,就找到了https://leetcode.com/api/problems/algorithms/返回的是json數據。稍微進行了一下分析(這個本身看一下數據,很容易發現的,雖然leetcode沒有api描述頁),就能夠知道stat
中的frontend_question_id
是id
,question__title_slug
對應的url
的地址,question__title
對應的是問題的名字,paid_only
表示是否須要購買。difficulty
表示難度.。而後咱們能夠出獲取LeetCode信息的代碼。編程
def get_leetcode_problems(self):
""" used to get leetcode inform :return: """
# we should look the response data carefully to find law
# return byte. content type is byte
content = requests.get('https://leetcode.com/api/problems/algorithms/').content
# get all problems
self.questions = json.loads(content)['stat_status_pairs']
# print(self.questions)
difficultys = ['Easy', 'Medium', 'Hard']
for i in range(len(self.questions) - 1, -1, -1):
question = self.questions[i]
name = question['stat']['question__title']
url = question['stat']['question__title_slug']
id_ = str(question['stat']['frontend_question_id'])
if int(id_) < 10:
id_ = '00' + id_
elif int(id_) < 100:
id_ = '0' + id_
lock = question['paid_only']
if lock:
self.locked += 1
difficulty = difficultys[question['difficulty']['level'] - 1]
url = Config.leetcode_url + url + '/description/'
q = Question(id_, name, url, lock, difficulty)
# 這裏後面咱們會放到類裏面,因此不用擔憂
# 之因此用一個table和table_item就是由於,咱們後期已經用什麼語言解決題目的時候要進行索引
self.table.append(q.id_)
self.table_item[q.id_] = q
return self.table, self.table_item
複製代碼
咱們須要一個東西記錄咱們完成狀況的類CompleteInform:json
class CompleteInform:
""" this is statistic inform, 用每種語言完成了多少題 """
def __init__(self):
self.solved = {
'python': 0,
'c++': 0,
'java': 0,
'javascript': 0
}
self.total = 0
def __repr__(self):
return str(self.solved)
複製代碼
而後咱們根據題目信息來創建題目對應的文件夾,api
def __create_folder(self, oj_name):
""" oj_name後面會傳入'leetcode',這裏這麼作就是後期,我想擴展生成別的oj的table """
oj_algorithms = Config.local_path + '/' + oj_name + '-algorithms'
if os.path.exists(oj_algorithms):
print(oj_name, ' algorithms is already exits')
else:
print('creating {} algorithms....'.format(oj_name))
os.mkdir(oj_algorithms)
for item in self.table_item.values():
question_folder_name = oj_algorithms + '/' + item.id_ + '. ' + item.title
if not os.path.exists(question_folder_name):
print(question_folder_name + 'is not exits, create it now....')
os.mkdir(question_folder_name)
# 這裏都會傳入一個‘leetcode',設置oj名字就是爲了方便擴展
def update_table(self, oj):
# the complete inform should be update
complete_info = CompleteInform()
self.get_leetcode_problems()
# the total problem nums
complete_info.total = len(self.table)
self.__create_folder(oj)
oj_algorithms = Config.local_path + '/' + oj + '-algorithms'
# 查看os.walk看具體返回的是什麼東西
for _, folders, _ in os.walk(oj_algorithms):
for folder in folders:
for _, _, files in os.walk(os.path.join(oj_algorithms, folder)):
if len(files) != 0:
complete_info.complete_num += 1
for item in files:
if item.endswith('.py'):
# 這個部分能夠寫成函數,不過我好像設計有點問題,不太好重構,請讀者本身思考
complete_info.solved['python'] += 1
folder_url = folder.replace(' ', "%20")
folder_url = os.path.join(folder_url, item)
folder_url = os.path.join(Config.github_leetcode_url, folder_url)
self.table_item[folder[:3]].python = '[python]({})'.format(folder_url)
elif item.endswith('.java'):
complete_info.solved['java'] += 1
folder_url = folder.replace(' ', "%20")
folder_url = os.path.join(folder_url, item)
folder_url = os.path.join(Config.github_leetcode_url, folder_url)
self.table_item[folder[:3]].java = '[Java]({})'.format(folder_url)
elif item.endswith('.cpp'):
complete_info.solved['c++'] += 1
folder_url = folder.replace(' ', "%20")
folder_url = os.path.join(folder_url, item)
folder_url = os.path.join(Config.github_leetcode_url, folder_url)
self.table_item[folder[:3]].c_plus_plus = '[C++]({})'.format(folder_url)
elif item.endswith('.js'):
complete_info.solved['javascript'] += 1
folder_url = folder.replace(' ', "%20")
folder_url = os.path.join(folder_url, item)
folder_url = os.path.join(Config.github_leetcode_url, folder_url)
self.table_item[folder[:3]].javascript = '[JavaScript]({})'.format(folder_url)
# 這裏使用到的Readme這個類就是寫文件,相對不是特別重要,沒什麼好講的
readme = Readme(complete_info.total, complete_info.complete_num, complete_info.solved)
readme.create_leetcode_readme([self.table, self.table_item])
print('-------the complete inform-------')
print(complete_info.solved)
複製代碼
上面需用用到的Readme類,用來生成README.md,只是進行了文件的讀寫,相對比較簡單。聰明的你確定一看就知道了。(只須要了解一點markdown中表格的生成規則)
class Readme:
""" generate folder and markdown file update README.md when you finish one problem by some language """
def __init__(self, total, solved, others):
""" :param total: total problems nums :param solved: solved problem nums :param others: 暫時還沒用,我想作擴展 """
self.total = total
self.solved = solved
self.others = others
self.time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.msg = '# Keep thinking, keep alive\n' \
'Until {}, I have solved **{}** / **{}** problems. ' \
'\n\nCompletion statistic: ' \
'\n1. JavaScript: {javascript} ' \
'\n2. Python: {python}' \
'\n3. C++: {c++}' \
'\n4. Java: {java}' \
'\n\nNote: :lock: means you need to buy a book from LeetCode\n'.format(
self.time, self.solved, self.total, **self.others)
def create_leetcode_readme(self, table_instance):
""" create REAdME.md :return: """
file_path = Config.local_path + '/README.md'
# write some basic inform about leetcode
with open(file_path, 'w') as f:
f.write(self.msg)
f.write('\n----------------\n')
with open(file_path, 'a') as f:
f.write('## LeetCode Solution Table\n')
f.write('| ID | Title | Difficulty | JavaScript | Python | C++ | Java |\n')
f.write('|:---:' * 7 + '|\n')
table, table_item = table_instance
for index in table:
item = table_item[index]
if item.lock:
_lock = ':lock:'
else:
_lock = ''
data = {
'id': item.id_,
'title': '[{}]({}) {}'.format(item.title, item.url, _lock),
'difficulty': item.difficulty,
'js': item.javascript if item.javascript else 'To Do',
'python': item.python if item.python else 'To Do',
'c++': item.c_plus_plus if item.c_plus_plus else 'To Do',
'java': item.java if item.java else 'To Do'
}
line = '|{id}|{title}|{difficulty}|{js}|{python}|{c++}|{java}|\n'.format(**data)
f.write(line)
print('README.md was created.....')
複製代碼
完整代碼請看:(這個能夠跑,歡迎使用)
#!/usr/bin/env python
# Created by Bruce yuan on 18-1-22.
import requests
import os
import json
import time
class Config:
""" some config, such as your github page 這裏須要配置你本身的項目地址 1. 本地倉庫的的路徑 2. github中的倉庫leetcode解法的路徑 """
local_path = '/home/yuan/PycharmProjects/algorithms_and_oj'
# solution of leetcode
github_leetcode_url = 'https://github.com/hey-bruce/algorithms_and_oj/blob/master/leetcode-algorithms/'
# solution of pat, 暫時還沒寫
github_pat_url = 'https://github.com/hey-bruce/algorithms_and_oj/blob/master/pat-algorithms/'
leetcode_url = 'https://leetcode.com/problems/'
class Question:
""" this class used to store the inform of every question """
def __init__(self, id_, name, url, lock, difficulty):
self.id_ = id_
self.title = name
# the problem description url 問題描述頁
self.url = url
self.lock = lock # boolean,鎖住了表示須要購買
self.difficulty = difficulty
# the solution url
self.python = ''
self.java = ''
self.javascript = ''
self.c_plus_plus = ''
def __repr__(self):
""" 沒啥用,我爲了調試方便寫的 :return: """
return str(self.id_) + ' ' + str(self.title) + ' ' + str(self.url)
class TableInform:
def __init__(self):
# raw questions inform
self.questions = []
# this is table index
self.table = []
# this is the element of question
self.table_item = {}
self.locked = 0
def get_leetcode_problems(self):
""" used to get leetcode inform :return: """
# we should look the response data carefully to find law
# return byte. content type is byte
content = requests.get('https://leetcode.com/api/problems/algorithms/').content
# get all problems
self.questions = json.loads(content)['stat_status_pairs']
# print(self.questions)
difficultys = ['Easy', 'Medium', 'Hard']
for i in range(len(self.questions) - 1, -1, -1):
question = self.questions[i]
name = question['stat']['question__title']
url = question['stat']['question__title_slug']
id_ = str(question['stat']['frontend_question_id'])
if int(id_) < 10:
id_ = '00' + id_
elif int(id_) < 100:
id_ = '0' + id_
lock = question['paid_only']
if lock:
self.locked += 1
difficulty = difficultys[question['difficulty']['level'] - 1]
url = Config.leetcode_url + url + '/description/'
q = Question(id_, name, url, lock, difficulty)
self.table.append(q.id_)
self.table_item[q.id_] = q
return self.table, self.table_item
# create problems folders
def __create_folder(self, oj_name):
oj_algorithms = Config.local_path + '/' + oj_name + '-algorithms'
if os.path.exists(oj_algorithms):
print(oj_name, ' algorithms is already exits')
else:
print('creating {} algorithms....'.format(oj_name))
os.mkdir(oj_algorithms)
for item in self.table_item.values():
question_folder_name = oj_algorithms + '/' + item.id_ + '. ' + item.title
if not os.path.exists(question_folder_name):
print(question_folder_name + 'is not exits, create it now....')
os.mkdir(question_folder_name)
def update_table(self, oj):
# the complete inform should be update
complete_info = CompleteInform()
self.get_leetcode_problems()
# the total problem nums
complete_info.total = len(self.table)
complete_info.lock = self.locked
self.__create_folder(oj)
oj_algorithms = Config.local_path + '/' + oj + '-algorithms'
# 查看os.walk看具體返回的是什麼東西
for _, folders, _ in os.walk(oj_algorithms):
for folder in folders:
for _, _, files in os.walk(os.path.join(oj_algorithms, folder)):
# print(files)
if len(files) != 0:
complete_info.complete_num += 1
for item in files:
if item.endswith('.py'):
complete_info.solved['python'] += 1
folder_url = folder.replace(' ', "%20")
folder_url = os.path.join(folder_url, item)
folder_url = os.path.join(Config.github_leetcode_url, folder_url)
self.table_item[folder[:3]].python = '[Python]({})'.format(folder_url)
elif item.endswith('.java'):
complete_info.solved['java'] += 1
folder_url = folder.replace(' ', "%20")
folder_url = os.path.join(folder_url, item)
folder_url = os.path.join(Config.github_leetcode_url, folder_url)
self.table_item[folder[:3]].java = '[Java]({})'.format(folder_url)
elif item.endswith('.cpp'):
complete_info.solved['c++'] += 1
folder_url = folder.replace(' ', "%20")
folder_url = os.path.join(folder_url, item)
folder_url = os.path.join(Config.github_leetcode_url, folder_url)
self.table_item[folder[:3]].c_plus_plus = '[C++]({})'.format(folder_url)
elif item.endswith('.js'):
complete_info.solved['javascript'] += 1
folder_url = folder.replace(' ', "%20")
folder_url = os.path.join(folder_url, item)
folder_url = os.path.join(Config.github_leetcode_url, folder_url)
self.table_item[folder[:3]].javascript = '[JavaScript]({})'.format(folder_url)
readme = Readme(complete_info.total,
complete_info.complete_num,
complete_info.lock,
complete_info.solved)
readme.create_leetcode_readme([self.table, self.table_item])
print('-------the complete inform-------')
print(complete_info.solved)
class CompleteInform:
""" this is statistic inform """
def __init__(self):
self.solved = {
'python': 0,
'c++': 0,
'java': 0,
'javascript': 0
}
self.complete_num = 0
self.lock = 0
self.total = 0
def __repr__(self):
return str(self.solved)
class Readme:
""" generate folder and markdown file update README.md when you finish one problem by some language """
def __init__(self, total, solved, locked, others):
""" :param total: total problems nums :param solved: solved problem nums :param others: 暫時還沒用,我想作擴展 """
self.total = total
self.solved = solved
self.others = others
self.locked = locked
self.time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.msg = '# Keep thinking, keep alive\n' \
'Until {}, I have solved **{}** / **{}** problems ' \
'while **{}** are still locked.' \
'\n\nCompletion statistic: ' \
'\n1. JavaScript: {javascript} ' \
'\n2. Python: {python}' \
'\n3. C++: {c++}' \
'\n4. Java: {java}' \
'\n\nNote: :lock: means you need to buy a book from LeetCode\n'.format(
self.time, self.solved, self.total, self.locked, **self.others)
def create_leetcode_readme(self, table_instance):
""" create REAdME.md :return: """
file_path = Config.local_path + '/README.md'
# write some basic inform about leetcode
with open(file_path, 'w') as f:
f.write(self.msg)
f.write('\n----------------\n')
with open(file_path, 'a') as f:
f.write('## LeetCode Solution Table\n')
f.write('| ID | Title | Difficulty | JavaScript | Python | C++ | Java |\n')
f.write('|:---:' * 7 + '|\n')
table, table_item = table_instance
for index in table:
item = table_item[index]
if item.lock:
_lock = ':lock:'
else:
_lock = ''
data = {
'id': item.id_,
'title': '[{}]({}) {}'.format(item.title, item.url, _lock),
'difficulty': item.difficulty,
'js': item.javascript if item.javascript else 'To Do',
'python': item.python if item.python else 'To Do',
'c++': item.c_plus_plus if item.c_plus_plus else 'To Do',
'java': item.java if item.java else 'To Do'
}
line = '|{id}|{title}|{difficulty}|{js}|{python}|{c++}|{java}|\n'.format(**data)
f.write(line)
print('README.md was created.....')
def main():
table = TableInform()
table.update_table('leetcode')
if __name__ == '__main__':
main()
複製代碼
歡迎使用,歡迎star,Happy Coding!
做者:BBruceyuan(袁朝發)
Github:github.com/bbruceyuan
知乎專欄:打點醬油
簡書地址:打點醬油
微信公衆號:動手學編程