index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
57,905
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/array/p0051_N-Queens.py
""" 51. N-Queens Hard The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively. """ class Solution: def __init__(self): self.res = [] def solveNQueens(self, n: int) -> List[List[str]]: board = [["."] * n for _ in range(0, n)] self.backtrace(board, 0) return self.res def backtrace(self, board, row): if row == len(board): board2 = ["".join(row) for row in board] self.res.append(board2) return n = len(board[row]) for col in range(n): if not self.isValid(board, row, col): continue # make choice board[row][col] = "Q" # move self.backtrace(board, row + 1) # backtrace board[row][col] = "." def isValid(self, board, row, col): n = len(board) # 决断列是否冲突 for r in range(n): if board[r][col] == "Q": return False # 决断左上方是否冲突 r, c = row - 1, col - 1 while r >= 0 and c >= 0: if board[r][c] == "Q": return False r -= 1 c -= 1 # 决断右上方是否冲突 r, c = row - 1, col + 1 while r >= 0 and c < n: if board[r][c] == "Q": return False r -= 1 c += 1 return True
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,906
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/stack/p0225_Implement_Stack_using_Queues.py
""" 225. Implement Stack using Queues Easy Implement a last in first out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal queue (push, top, pop, and empty). Implement the MyStack class: void push(int x) Pushes element x to the top of the stack. int pop() Removes the element on the top of the stack and returns it. int top() Returns the element on the top of the stack. boolean empty() Returns true if the stack is empty, false otherwise. Notes: You must use only standard operations of a queue, which means only push to back, peek/pop from front, size, and is empty operations are valid. Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue), as long as you use only a queue's standard operations. """ class MyStack: def __init__(self): """ Initialize your data structure here. """ self.queues = [] def push(self, x: int) -> None: """ Push element x onto stack. """ self.queues.append(x) def pop(self) -> int: """ Removes the element on top of the stack and returns that element. """ return self.queues.pop() def top(self) -> int: """ Get the top element. """ return self.queues[-1] def empty(self) -> bool: """ Returns whether the stack is empty. """ return not self.queues # Your MyStack object will be instantiated and called as such: # obj = MyStack() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.top() # param_4 = obj.empty()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,907
klgentle/lc_python
refs/heads/master
/base_practice/ava.py
number_file = open("numbers.txt", "r") total = 0 count = 0 ave = 0 num = number_file.readline() while num != "": amount = int(num) total += amount count += 1 num = number_file.readline() number_file.close() ave = total / count print(format(ave, ".1f"))
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,908
klgentle/lc_python
refs/heads/master
/stock_pandas/assignment2.py
import requests url = "https://sites.google.com/site/chnyyang/price_data.csv" f = requests.get(url) with open("price_data.csv", "wb") as code: code.write(f.content)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,909
klgentle/lc_python
refs/heads/master
/leet_code/easy_case/p0020_Valid_Parentheses.py
from typing import List, Any from pysnooper import snoop class Solution: @snoop() def isValid(self, s: str) -> bool: if not s: return True if len(s) % 2 == 1: return False pair_bracket = {"(": ")", "{": "}", "[": "]", ")": "(", "}": "{", "]": "["} bracket_stock = [] bracket_stock.append(s[0]) # bracket put into stock for i in range(1, len(s)): # is pair, bracket_stock pop if bracket_stock and pair_bracket.get(s[i]) == bracket_stock[-1]: bracket_stock.pop() else: bracket_stock.append(s[i]) if len(bracket_stock) == 0: return True else: return False if __name__ == "__main__": o = Solution() s = "()[]{}" o.isValid(s)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,910
klgentle/lc_python
refs/heads/master
/leet_code/easy_case/generate.py
import pysnooper class Solution: @pysnooper.snoop() def generate(self, numRows: int) -> list: if not numRows: return [] ret = [[1],[1,1]] for j in range(2,numRows): row = [1] last_list = ret[-1] print(f"len(last_list):{len(last_list)}") for i in range(1,len(last_list)): row.append(last_list[i-1]+last_list[i]) ret.append(row + [1]) print(f"ret:{ret}") return ret if __name__ == "__main__": a = Solution() a.generate(5)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,911
klgentle/lc_python
refs/heads/master
/GUI/my_window.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # author:洪卫 import tkinter as tk # 使用Tkinter前需要先导入 # 第1步,实例化object,建立窗口window window = tk.Tk() # 第2步,给窗口的可视化起名字 window.title("My Window") # 第3步,设定窗口的大小(长 * 宽) window.geometry("600x400") # 这里的乘是小x # 第4步,在图形界面上设定标签 var = tk.StringVar() # 将label标签的内容设置为字符类型,用var来接收hit_me函数的传出内容用以显示在标签上 l = tk.Label( window, textvariable=var, bg="green", fg="white", font=("Arial", 12), width=30, height=2, ) # 说明: bg为背景,font为字体,width为长,height为高,这里的长和高是字符的长和高,比如height=2,就是标签有2个字符这么高 # 第5步,放置标签 l.pack() # Label内容content区域放置位置,自动调节尺寸 # 放置lable的方法有:1)l.pack(); 2)l.place(); # 定义一个函数功能(内容自己自由编写),供点击Button按键时调用,调用命令参数command=函数名 on_hit = False def hit_me(): global on_hit if on_hit == False: on_hit = True var.set("you hit me") else: on_hit = False var.set("") # 第5步,在窗口界面设置放置Button按键 b = tk.Button( window, text="hit me", font=("Arial", 12), width=10, height=1, command=hit_me ) b.pack() # 第6步,主窗口循环显示 window.mainloop() # 注意,loop因为是循环的意思,window.mainloop就会让window不断的刷新,如果没有mainloop,就是一个静态的window,传入进去的值就不会有循环,mainloop就相当于一个很大的while循环,有个while,每点击一次就会更新一次,所以我们必须要有循环 # 所有的窗口文件都必须有类似的mainloop函数,mainloop是窗口文件的关键的关键。
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,912
klgentle/lc_python
refs/heads/master
/base_practice/for_sep.py
for i in range(5): print(i,'hello','kkkl',sep='')
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,913
klgentle/lc_python
refs/heads/master
/base_practice/translator.py
def jiugongge_letter_to_number(phoneNum) -> str: """老手机中的九宫格字母转为对应的数字""" # phoneNum = input("Enter a phone number to be translated: ") # phoneNum = "555-GET-FOOD" phoneNum = phoneNum.upper() phoneNum_list = phoneNum.split("-") # ['555','GET','FOOD'] for j in range(len(phoneNum_list)): # 'GET' var = phoneNum_list[j] if var.isdigit(): continue var2 = [0] * len(var) for i in range(len(var)): if var[i] == "A" or var[i] == "B" or var[i] == "C": var2[i] = "2" elif var[i] == "D" or var[i] == "E" or var[i] == "F": var2[i] = "3" elif var[i] == "G" or var[i] == "H" or var[i] == "I": var2[i] = "4" elif var[i] == "J" or var[i] == "K" or var[i] == "L": var2[i] = "5" elif var[i] == "M" or var[i] == "N" or var[i] == "O": var2[i] = "6" elif var[i] == "P" or var[i] == "Q" or var[i] == "R" or var[i] == "S": var2[i] = "7" elif var[i] == "T" or var[i] == "U" or var[i] == "V": var2[i] = "8" elif var[i] == "W" or var[i] == "X" or var[i] == "Y" or var[i] == "Z": var2[i] = "9" # print(f"var2:{var2}") phoneNum_list[j] = "".join(var2) phoneNum1 = "-".join(phoneNum_list) # print(phoneNum1) return phoneNum1 if __name__ == "__main__": phoneNum = input("Enter a phone number to be translated: ") print(jiugongge_letter_to_number(phoneNum))
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,914
klgentle/lc_python
refs/heads/master
/stock_pandas/plt_bar.py
import matplotlib.pyplot as plt import pandas as pd # x 是x轴,y是y轴, loan = pd.read_csv("loan.csv") x = [625, 650, 675, 700, 725, 750, 775, 800] y = [2.0, 2.0, 1.0, 3.0, 4.0, 2.0, 1.0, 2.0] p1 = plt.bar(x, height=y, width=25) plt.title("Credit_score") plt.grid(axis='y') plt.grid(axis='x') plt.show()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,915
klgentle/lc_python
refs/heads/master
/leet_code/medium_case/P0018_4sum.py
""" Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: The solution set must not contain duplicate quadruplets. """ class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: def findSum(nums, target, N, result, results): if len(nums) < N or N < 2 or nums[0] * N > target or nums[-1] * N < target: return if N == 2: l, r = 0, len(nums) - 1 while l < r: total = nums[l] + nums[r] if total == target: results.append(result + [nums[l], nums[r]]) l += 1 # pass the duplicate # if nums[l] is the same with nums[l-1], then no need to consider nums[l] while (l < r and nums[l] == nums[l - 1]): l += 1 elif total < target: l += 1 else: r -= 1 else: # find recursive for i in range(len(nums) - N + 1): if i == 0 or (i > 0 and nums[i - 1] != nums[i]): findSum( nums[i + 1 :], target - nums[i], N - 1, result + [nums[i]], results, ) results = [] findSum(sorted(nums), target, 4, [], results) return results
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,916
klgentle/lc_python
refs/heads/master
/database/batch_replace.py
import os import sys import logging logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") # 绝对路径的import sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../") # from database.FindViewOriginalTable import FindViewOriginalTable # from database.Procedure import Procedure from database.ProcedureLogModify import ProcedureLogModify from database.AutoViewReplace import AutoViewReplace def run_replace_view(proc_name: str, schema="RPTUSER"): # modify view name, data_area proc_view = AutoViewReplace() proc_view.main(proc_name, schema) def run_modify_log(proc_name: str, schema="RPTUSER"): # modify log # TODO add schema proc_log = ProcedureLogModify(proc_name) proc_log.main() def read_file_to_list(file_name: str) -> list: name_list = [] with open(file_name, "r") as file: cont = file.read() name_list = cont.split("\n") return name_list def batch_replace(proc_list: list, replace_type="view_and_log"): error_dict = {} for content in proc_list: proc, schema = content.split("\t") if not schema: schema = "RPTUSER" # print(f"content:{content}") # print(f"proc:{proc}") # print(f"schema:{schema}") # modify view name, data_area try: # proc_view = AutoViewReplace() # proc_view.main(proc) if replace_type == "view": run_replace_view(proc, schema) elif replace_type == "log": run_modify_log(proc, schema) else: run_replace_view(proc, schema) run_modify_log(proc, schema) except Exception as e: # error_dict[proc] = e.__str__ error_dict[proc] = e.__doc__ print(f"error, {proc}, {schema}") return error_dict if __name__ == "__main__": # if len(sys.argv) <= 1: # logging.info("Please input procedure_name") # sys.exit(1) file_name = r"E:\yx_walk\report_develop\view_to_replace\loan_list.txt" # proc_list = read_file_to_list(file_name) # proc_list = ["p_rpt_" + x.lower() for x in proc_list] # proc_list = ["p_itf_" + x.lower() for x in proc_list] proc_list = [ "P_RPT_AFT019E RPTUSER_MO", "P_RPT_CIF114D1 RPTUSER_MO", "P_RPT_CIF114D5 RPTUSER_MO", "P_RPT_ILN160 RPTUSER_MO", "P_RPT_ILN180B RPTUSER_MO", "P_RPT_ILN200 RPTUSER_MO", "P_RPT_ILN200R RPTUSER_MO", "P_RPT_ILN250 RPTUSER_MO", "P_RPT_ILN250A RPTUSER_MO", "P_RPT_MACOA410 RPTUSER_MO", "P_RPT_MOR160 RPTUSER_MO", ] ###error_dict = batch_replace(proc_list, "view_and_log") # 尽量少改动 error_dict = batch_replace(proc_list, "view") print("-------------", error_dict)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,917
klgentle/lc_python
refs/heads/master
/Intermediate_Python/except_e_args.py
try: file = open("text.txt", "rb") except IOError as e: print("An IOError occured. {}".format(e.args[-1]))
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,918
klgentle/lc_python
refs/heads/master
/leet_code/easy_case/maxSubArray.py
class Solution: def maxSubArray(self, nums: list) -> int: max_nums = max(nums) sum_nums = sum(nums) max_sum = max(max_nums, sum_nums) l = len(nums) print(f"max_sum:{max_sum}") if l == 1 or max_sum < 0: return max_sum m,n = 0,l max_list = nums for i,k in enumerate(nums): if k < 0: m += 1 break print(f"max_sum:{max_sum}") return max_sum if __name__ == '__main__': a = Solution() l = [-2, -1] a.maxSubArray(l)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,919
klgentle/lc_python
refs/heads/master
/database/Procedure.py
import time import sys import os import re import logging # 项目根目录 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 添加系统环境变量 sys.path.append(BASE_DIR) # 导入模块 from database.convert_file_to_utf8 import convert_file_to_utf8 from string_code.StringFunctions import StringFunctions from decorator_test.logging_decorator import logging_begin_end logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s") # define constant variable AND_DATA_AREA_PATTERN = r"\sAND\s+(\w*.)?DATA_AREA" ON_DATA_AREA_PATTERN = r"\sON\s+(\w*.)?DATA_AREA" WHERE_DATA_AREA_PATTERN = r"WHERE\s+(\w*.)?DATA_AREA" class ProcedureTypeError(TypeError): pass class ProcedureValueError(ValueError): pass class Procedure(object): """ procedure deal with path, procedure file name use re.sub(pattern, repl, string, flags=re.IGNORECASE) instead of str.replace() """ def __init__(self, proc_name: str, schema="RPTUSER"): # self.__procedure_path = r"E:\svn\1300_编码\1301_ODSDB\RPTUSER\05Procedures" # svn bak path # to DEPART FH00 AND FM00 self.__schema = schema.upper() self.__procedure_path = r"E:\svn\1300_编码\1301_ODSDB\{}\98Procedures_bak_20191016".format( self.__schema ) self.__proc_name = proc_name # raise error if not os.path.exists( os.path.join(self.__procedure_path, self.get_file_name()) ): raise ValueError("Procedure name is incorrect!") self.file_to_utf8() self.add_schema() self.__date_str = time.strftime("%Y%m%d", time.localtime()) self.__note = "-- DONGJIAN {} ".format(self.__date_str) # self.modify_proc_by_line() # skip no need # self.delete_no_used_code() def file_to_utf8(self): return convert_file_to_utf8( os.path.join(self.__procedure_path, self.get_file_name()) ) def get_file_name(self) -> str: return self.__proc_name + ".sql" def add_schema(self): """ CHANGE FROM V_, JOIN V_ TO FROM RPTUSER.V_, JOIN RPTUSER.V_ """ proc_cont = self.read_proc_cont() pattern = r"(from|join)\s+(v|rpt)_" search_obj = re.search(pattern, proc_cont, flags=re.IGNORECASE) if search_obj: # add RPTUSER proc_cont = re.sub( pattern, r"\1 {}.\2_".format(self.__schema), proc_cont, flags=re.IGNORECASE ) self.write_procedure(proc_cont) # @logging_begin_end def delete_no_used_code(self): """ """ proc_cont = self.read_proc_cont() pattern = r"--\s*-V_SPEND_TIME\s*:=\s*V_END_TIME\s*-\s*V_ST_TIME ;(----执行时间)?" search_obj = re.search(pattern, proc_cont, flags=re.IGNORECASE) if search_obj: proc_cont = re.sub(pattern, r"", proc_cont, flags=re.IGNORECASE) self.write_procedure(proc_cont) @staticmethod def split_line_with_two_and(line: str): """more than one AND to add \n ON B1.ID = B3.ID AND B1.DATA_AREA = B3.DATA_AREA AND B1.DATA_DATE = B3.DATA_DATE """ find_list = re.findall(r" AND ", line) if len(find_list) > 1: line_strip = line.strip() # do not split and "between add" if re.search("BETWEEN", line, flags=re.IGNORECASE): return line # deal with AND C.M = 1 AND C.S = 1 if re.search( r"(\w*.)?M\s*=\s*(')?1(')?\s*AND\s+(\w*.)?S\s*=\s*(')?1(')?", line, flags=re.IGNORECASE, ): return line line = line.upper() if not line_strip.startswith("--") and not line_strip.startswith("WHEN"): line_obj = StringFunctions(line) second_position = line_obj.find_the_second_position(" AND ") logging.info("split line with two add") line = line_obj.str_insert(second_position, "\n") return line @staticmethod def delete_blank_of_job_step(line: str) -> str: job_step_pattern = r"\s*V_JOB_STEP\s*:=\s*(\d)+\s*;\s*" if re.search(job_step_pattern, line, flags=re.IGNORECASE): line = re.sub( job_step_pattern, r"V_JOB_STEP:=\1;\n", line, flags=re.IGNORECASE ) return line # @logging_begin_end def modify_proc_by_line(self): proc_cont_list = [] proc_file_name = self.get_file_name() with open( os.path.join(self.__procedure_path, proc_file_name), "r", encoding="UTF-8" ) as pro: proc_cont_list = pro.readlines() logging.info("modify proc by line") for i in range(0, len(proc_cont_list)): line = proc_cont_list[i] proc_cont_list[i] = self.split_line_with_two_and(line) # no need # proc_cont_list[i] = self.delete_blank_of_job_step(line) self.write_procedure("".join(proc_cont_list)) def write_procedure(self, proc_cont: str): proc_file_name = self.get_file_name() with open( os.path.join(self.__procedure_path, proc_file_name), "w", encoding="UTF-8" ) as pro: pro.write(proc_cont) def read_proc_cont(self) -> str: proc_cont = "" proc_file_name = self.get_file_name() with open( os.path.join(self.__procedure_path, proc_file_name), "r", encoding="UTF-8" ) as pro: proc_cont = pro.read() # .upper() return proc_cont @logging_begin_end def replace_view_with_table(self, view_dict: dict): proc_cont = self.read_proc_cont() for view, table in view_dict.items(): # TODO shema if self.__schema == "RPTUSER_MO": table = table.replace("FH00", "FM00") view_pattern = r"(RPTUSER.|RPTUSER_MO.)?{}".format(view) try: proc_cont = re.sub(view_pattern, table, proc_cont, flags=re.IGNORECASE) except Exception as e: logging.error("view: ", view, e.__doc__) self.write_procedure(proc_cont) @staticmethod def data_area_check(line: str) -> bool: line = line.upper() if ( not line.strip().startswith("--") and line.find("DATA_AREA") > -1 and ( re.search(AND_DATA_AREA_PATTERN, line, re.IGNORECASE) or re.search(ON_DATA_AREA_PATTERN, line, re.IGNORECASE) or re.search(WHERE_DATA_AREA_PATTERN, line, re.IGNORECASE) ) ): return True return False @staticmethod def add_header_log(proc_cont: str, modify_content="log modify") -> str: """添加起始位置的log登记 如: V1.0 20180515 HASON 1.ADD SCHEMA """ date_str = time.strftime("%Y%m%d", time.localtime()) header_log = " V2.0 {0} \tdongjian {1}\n".format(date_str, modify_content) log_end = "+====================" if proc_cont.find(log_end) > -1: proc_cont = proc_cont.replace(log_end, header_log + log_end) return proc_cont def write_header_log(self, modify_content="log modify") -> None: """将添加头部log登记的内容写入文件 """ proc_cont = self.add_header_log(self.read_proc_cont(), modify_content) self.write_procedure(proc_cont) def data_area_replace(self, line: str) -> str: """ 按行读取,如果出现了 ON DATA_AREA, AND DATA_AREA, WHERE DATA_AREA,则进行替换,添加-- ON, WHERE -> ON 1=1 -- OR WHERE 1=1 -- AND -> -- AND ) -> \n) """ try: if self.data_area_check(line): line = self.add_header_log(line, "data_area replace") logging.debug("data_area处理") line = line.upper() if re.search(AND_DATA_AREA_PATTERN, line, re.IGNORECASE): line = re.sub(AND_DATA_AREA_PATTERN, r" --AND \1DATA_AREA", line) elif re.search(ON_DATA_AREA_PATTERN, line, re.IGNORECASE): line = re.sub(ON_DATA_AREA_PATTERN, r" ON 1=1 --\1DATA_AREA", line) elif re.search(WHERE_DATA_AREA_PATTERN, line, re.IGNORECASE): line = re.sub( WHERE_DATA_AREA_PATTERN, r"WHERE 1=1 --\1DATA_AREA", line ) # replace line end if line.find(")") > -1: line = line.replace(")", "\n)") if line.find(";") > -1: line = line.replace(";", "\n;") if line.find("*/") > -1: line = line.replace("*/", "\n*/") # delete line if line.count("\n") <= 1 and line.strip().startswith("--"): line = "" else: # line add note in the end line = "".join([line[:-1], self.__note, "\n"]) except: logging.error(f"line deal failed, line: {line}") return line def deal_data_area_in_sub_select(self) -> None: """ 处理子查询的data_area case 0: some_filed1, T.data_area, some_filed2 case 1: ,T.data_area\n ,some_filed\n case 2: T.data_area,\n some_filed,\n question re.sub替换了两个\n: re \s matches any whitespace character, this is equivalent to the set [ \t\n\r\f\v]. """ logging.debug("deal data_area in select") proc_cont = self.read_proc_cont() comma_around_data_area = r",\s*(\w*.)?DATA_AREA\s*," # case 1, 2, 3 comma_before_or_after_data_area = r"(\s*)(,)?\s*(\w*.)?DATA_AREA\s*(,)?\s*" proc_cont = re.sub(comma_around_data_area, r",", proc_cont, flags=re.IGNORECASE) proc_cont = re.sub( comma_before_or_after_data_area, r"\1", proc_cont, flags=re.IGNORECASE ) self.write_procedure(proc_cont) @logging_begin_end def data_area_deal(self): """处理data_area """ proc_cont_list = [] proc_file_name = self.get_file_name() with open( os.path.join(self.__procedure_path, proc_file_name), "r", encoding="UTF-8" ) as pro: proc_cont_list = pro.readlines() for index, line in enumerate(proc_cont_list): proc_cont_list[index] = self.data_area_replace(line) self.write_procedure("".join(proc_cont_list)) self.deal_data_area_in_sub_select() if __name__ == "__main__": # proc = Procedure('p_rpt_cif022') proc = Procedure("p_rpt_cif063") # proc.modify_proc_by_line() proc.add_schema()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,920
klgentle/lc_python
refs/heads/master
/svn_operate/send_mail_with_attach.py
#!/usr/bin/python3 import traceback import time import os import smtplib from email.mime.text import MIMEText from email.utils import formataddr from email.mime.multipart import MIMEMultipart # from pysnooper import snoop from getpass import getpass from sys import argv sender = "jian.dong2@pactera.com" # 发件人邮箱 # password = '' # 发件人邮箱密码 addressed_eamil2 = [ "jiaming.pan@pactera.com" ] # 收件人邮箱 'BenChanHY@chbank.com', # @snoop() def mail(date_str=None, file_path=""): """ 作者:梦忆安凉 原文:https://blog.csdn.net/a54288447/article/details/81113934 """ home_path = "/home/kl" time_str = time.strftime("%H:%M:%S", time.localtime()) if not os.path.exists(home_path): home_path = "/mnt/e" if not date_str: date_str = time.strftime("%Y%m%d", time.localtime()) if not file_path: file_path = f"{home_path}/yx_walk/beta/{date_str}beta.zip" # print(file_path) try: # 创建一个带附件的实例 message = MIMEMultipart() message["From"] = formataddr(["jdong", sender]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号 # send to multi people, 1.message to should join by comma, 2.sending to should be list message["To"] = formataddr( ["Dear", ",".join(addressed_eamil2)] ) # 括号里的对应收件人邮箱昵称、收件人邮箱账号 message["Subject"] = f"UAT {date_str}beta update {time_str}" # 邮件的主题,也可以说是标题 # 邮件正文内容 message.attach( MIMEText( f"Dear all,\n\n\tSIT, UAT program update {date_str}.\n\nBest Regards\nDong Jian", "plain", "utf-8", ) ) # 构造附件1 # att1 = MIMEText(open('D:/PycharmProjects/Vuiki/Common/测试.txt', 'rb').read(), 'base64', 'utf-8') # att1["Content-Type"] = 'application/octet-stream' ## filename是附件名,附件名称为中文时的写法 # att1.add_header("Content-Disposition", "attachment", filename=("gbk", "", "测试.txt")) # message.attach(att1) # 构造附件2 att2 = MIMEText(open(file_path, "rb").read(), "base64", "utf-8") att2["Content-Type"] = "application/octet-stream" # 附件名称非中文时的写法 att2["Content-Disposition"] = f'attachment; filename="{date_str}beta.zip")' message.attach(att2) # server = smtplib.SMTP_SSL("smtp.office365.com", 847) # 发件人邮箱中的SMTP服务器,一般端口是25 server = smtplib.SMTP("smtp.office365.com", 587) # 发件人邮箱中的SMTP服务器,一般端口是25 server.starttls() # to get passwd # password = getpass(f"{sender}'s password: ") cmd = "awk 'FS=\"=\" {if ($0~/^pactera_passwd/) print $2}' $HOME/.passwd.txt" password = "" with os.popen(cmd) as p: password = p.read() server.login(sender, password) # 括号中对应的是发件人邮箱账号、邮箱密码 # multi people shoud be list server.sendmail( sender, addressed_eamil2, message.as_string() ) # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件 server.quit() # 关闭连接 print("邮件发送成功") except Exception as e: traceback.print_exc() print("邮件发送失败") if __name__ == "__main__": date_str = time.strftime("%Y%m%d", time.localtime()) if len(argv) > 1 and len(argv[1]) == 8: date_str = argv[1] mail(date_str)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,921
klgentle/lc_python
refs/heads/master
/tests/testDealInterval.py
import os import sys from os.path import dirname import datetime import pprint import unittest # 项目根目录 BASE_DIR = dirname(dirname(os.path.abspath(__file__))) # 添加系统环境变量 sys.path.append(BASE_DIR) from automatic_office.DealInterval import DealInterval class testDealInterval(unittest.TestCase): def setUp(self): print("setUp...") self.report = DealInterval() self.date_tuple = (datetime.date(2020, 3, 5), datetime.date(2020, 3, 7)) def test_get_from_end_str(self): assert self.report.get_from_end_str(self.date_tuple) == "20200305-20200307" def test_get_from_date(self): assert self.report.get_from_date(self.date_tuple) == "2020-03-05" def test_get_end_date(self): assert self.report.get_end_date(self.date_tuple) == "2020-03-07" def test_get_one_weekday_interval(self): weekdays = [ datetime.date(2020, 3, 5), datetime.date(2020, 3, 6), datetime.date(2020, 3, 7), ] print("weekdays1", weekdays) assert self.report.get_all_weekday_interval(weekdays, []) == [ (datetime.date(2020, 3, 5), datetime.date(2020, 3, 7)) ] def test_get_two_weekday_interval(self): weekdays = [ datetime.date(2020, 3, 5), datetime.date(2020, 3, 6), datetime.date(2020, 3, 7), datetime.date(2020, 3, 13), datetime.date(2020, 3, 14), ] print("weekdays2", weekdays) print("out2") out = self.report.get_all_weekday_interval(weekdays, []) pprint.pprint(out) assert out == [ (datetime.date(2020, 3, 5), datetime.date(2020, 3, 7)), (datetime.date(2020, 3, 13), datetime.date(2020, 3, 14)), ] def test_get_three_weekday_interval_with_oneday_separate(self): weekdays = [ datetime.date(2020, 3, 5), datetime.date(2020, 3, 6), datetime.date(2020, 3, 7), datetime.date(2020, 3, 10), datetime.date(2020, 3, 13), datetime.date(2020, 3, 14), ] print("weekdays3", weekdays) out3 = self.report.get_all_weekday_interval(weekdays, []) print("out3", out3) assert out3 == [ (datetime.date(2020, 3, 5), datetime.date(2020, 3, 7)), (datetime.date(2020, 3, 10), datetime.date(2020, 3, 10)), (datetime.date(2020, 3, 13), datetime.date(2020, 3, 14)), ] def tearDown(self): print("tearDown...") if __name__ == "__main__": unittest.main()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,922
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/tree/P0116_Populating_Next_Right_Pointers_in_Each_Node.py
""" You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: struct Node { int val; Node *left; Node *right; Node *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL. # Definition for a Node. class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right self.next = next """ from typing import List, Node class Solution: def connect(self, root: "Node") -> "Node": if root is None: return root self.connectTwoNode(root.left, root.right) return root def connectTwoNode(self, node1: "None", node2: "None"): if node1 is None or node2 is None: return None # 连接顶点 node1.next = node2 self.connectTwoNode(node1.left, node1.right) self.connectTwoNode(node2.left, node2.right) self.connectTwoNode(node1.right, node2.left) if __name__ == "__main__": a = Solution() root = [1, 2, 3, 4, 5, 6, 7] print(a.connect(root))
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,923
klgentle/lc_python
refs/heads/master
/automatic_office/Holiday.py
import json import requests import os from datetime import datetime class Holiday(object): def is_holiday(self, date_str: str) -> bool: """ date_str: YYYYmmdd 周末上班对应结果为 0, 休息日对应结果为 1, 节假日对应的结果为 2 不上班有两种情况: 1: josn data is 1 or 2 2: weekend and josn data not equal to 0 """ year = date_str[0:4] day = date_str[4:] # ddmm with open(os.path.join("data","{}_data.json".format(year))) as f: data = json.loads(f.read()) # 国家规定上班与放假的情况 if data.get(day) in (1, 2): return True elif data.get(day) == 0: return False # 周末不上班的情况 date = datetime.strptime(date_str, "%Y%m%d").date() if date.weekday() in (5, 6): return True else: return False def api_holiday_not_used(self, date_str: str) -> bool: """ argv: date_str:yyyymmdd > 示例: --http://api.goseek.cn/Tools/holiday?date=20170528 --http://timor.tech/api/holiday/info/2019-11-26 http://www.easybots.cn/api/holiday.php?d= > 返回数据: "20200101":"2" """ api_url = r"http://www.easybots.cn/api/holiday.php?d={}".format(date_str) r = requests.get(api_url) resp = json.loads(r.text) # test # print(resp) # 工作日对应结果为 0, 休息日对应结果为 1, 节假日对应的结果为 2 return resp.get(date_str) in ("1", "2") def is_holiday_not_used(self, date_str: str) -> bool: return self.api_holiday(date_str) if __name__ == "__main__": obj = Holiday() # print(obj.api_holiday("20190929")) print(20200101) assert obj.is_holiday("20200101") is True print(20200130) assert obj.is_holiday("20200130") is True print(20200119) assert obj.is_holiday("20200119") is False print(20200118) assert obj.is_holiday("20200118") is True print(20200112) assert obj.is_holiday("20200112") is True print(20200326) assert obj.is_holiday("20200326") is False
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,924
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/tree/P0297_Serialize_and_Deserialize_Binary_Tree.py
""" Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself. """ class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ if not root: return "#" left = self.serialize(root.left) right = self.serialize(root.right) return f"{root.val},{left},{right}" def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ nodes = data.split(",") return self.deserializeIteration(nodes) def deserializeIteration(self, nodes): if not nodes: return None # print(f"nodes:{nodes}") root_val = nodes.pop(0) if root_val == "#": return None root = TreeNode(root_val) # 无法区分左右,直接交给递归. 递归会不断减少数据,left全部减少之后就只剩right root.left = self.deserializeIteration(nodes) root.right = self.deserializeIteration(nodes) return root # Your Codec object will be instantiated and called as such: # ser = Codec() # deser = Codec() # ans = deser.deserialize(ser.serialize(root))
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,925
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/sliding_window/p0239_Sliding_Window_Maximum.py
""" 239. Sliding Window Maximum Hard You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window. Example 1: Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 Output: [3,3,5,5,6,7] Explanation: Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7 Example 2: Input: nums = [1], k = 1 Output: [1] Example 3: Input: nums = [1,-1], k = 1 Output: [1,-1] Example 4: Input: nums = [9,11], k = 2 Output: [11] Example 5: Input: nums = [4,-2], k = 2 Output: [4] """ from collections import deque class MonotonicQueue: """ 使用 deque 比直接使用 list 实现会高效一些 """ def __init__(self): self.q = deque() def push(self, n): # 删除所有小于n的元素 while self.q and self.q[-1] < n: self.q.pop() self.q.append(n) def max(self): return self.q[0] def pop(self, n): if self.q[0] == n: self.q.popleft() class MonotonicQueue0: def __init__(self): self.q = [] def push(self, n): # 删除所有小于n的元素 while self.q and self.q[-1] < n: self.q.pop() self.q.append(n) def max(self): return self.q[0] def pop(self, n): if self.q[0] == n: self.q.pop(0) class Solution: def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: window = MonotonicQueue() res = [] for i, v in enumerate(nums): if i < k - 1: window.push(v) else: window.push(v) res.append(window.max()) window.pop(nums[i-k+1]) return res
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,926
klgentle/lc_python
refs/heads/master
/leet_code/top_interview_questions/Medium_Case/P0179_Largest_Number.py
class Solution: def largestNumber(self, nums: List[int]) -> str: # improve step by step if set(nums) == {0}: return "0" nums_str = [str(i) for i in nums] ret_len = len("".join(nums_str)) nums_str_ind = [[str(i),ind] for ind, i in enumerate(nums)] # '0', 'x' pad is not perfect, use the last digit to test, use the data it's self to test l = len(nums) #nums_test = [[d[0].ljust(ret_len,d[0]), d[1]] for d in nums_str_ind] # cope l times and return ret_len nums_test = [[(d[0]*l)[:ret_len], d[1]] for d in nums_str_ind] nums_order_desc = sorted(nums_test, key = lambda d: d[0], reverse=True) #print(f"nums_order_desc:{nums_order_desc}") ret = "" for d in nums_order_desc: ret += str(nums[d[1]]) return ret
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,927
klgentle/lc_python
refs/heads/master
/leet_code/easy_case/plusOne.py
class Solution: def plusOne(self, digits: list) -> list: l = len(digits) if digits[-1] < 9: digits[-1] += 1 elif digits[-1] == 9: digits[-1] = 10 for i in range(-1, -l, -1): # print(i) if digits[i] == 10: digits[i] = 0 digits[i - 1] += 1 if digits[0] == 10: digits = [1, 0] + digits[1:] print(f"digits:{digits}") return digits if __name__ == "__main__": a = Solution() a.plusOne([8, 2, 1, 9, 9, 9])
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,928
klgentle/lc_python
refs/heads/master
/database/cx_Oracle_test.py
from data_base_connect import connect #import cx_Oracle # use in linux or centos, not in windos (libclntsh.so: cannot open shared object file: No such file or directory) #conn = cx_Oracle.connect('rptuser', 'rptuser','100.11.94.176:1521/odsdb') conn = connect() cursor = conn.cursor() cursor.execute("select id from rpt_account_mid where data_date != date'2018-08-30'") #result = cursor.fetchall() #for row in result: # print(row[0]) result = cursor.fetchone() print(result[0]) cursor.close() conn.close()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,929
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/tree/p0099_Recover_Binary_Search_Tree.py
""" 99. Recover Binary Search Tree Hard You are given the root of a binary search tree (BST), where exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure. Follow up: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? Example 1: Input: root = [1,3,null,null,2] Output: [3,1,null,null,2] Explanation: 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid. Example 2: Input: root = [3,1,4,null,null,2] Output: [2,1,4,null,null,3] Explanation: 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid. """ class Solution: def __init__(self): self.val_list = [] def recoverTree(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ if not root: return # 先中序遍历一下,找到需要更改的位置,然后再来一遍,修改数据 self.tree2List(root) right_val = sorted(self.val_list) #print(f"right_val:{right_val}") root = self.correctTree(root, right_val) def tree2List(self, root): if not root: return self.tree2List(root.left) self.val_list.append(root.val) self.tree2List(root.right) def correctTree(self, root, right_val:list): if not root: return self.correctTree(root.left, right_val) val = right_val.pop(0) if root.val != val: root.val = val self.correctTree(root.right, right_val) return root
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,930
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/queue/p0232_Implement_Queue_using_Stacks.py
""" 232. Implement Queue using Stacks Easy Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty). Implement the MyQueue class: void push(int x) Pushes element x to the back of the queue. int pop() Removes the element from the front of the queue and returns it. int peek() Returns the element at the front of the queue. boolean empty() Returns true if the queue is empty, false otherwise. """ class MyQueue: def __init__(self): """ Initialize your data structure here. """ self.s1, self.s2 = [], [] def push(self, x: int) -> None: """ Push element x to the back of queue. """ self.s1.append(x) def pop(self) -> int: """ Removes the element from in front of queue and returns that element. """ self.peek() print(f"s2: {self.s2}") return self.s2.pop() def peek(self) -> int: """ Get the front element. """ if not self.s2: while self.s1: print(f"s1:{self.s1}") self.s2.append(self.s1.pop()) return self.s2[-1] def empty(self) -> bool: """ Returns whether the queue is empty. """ return not self.s1 and not self.s2 # Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,931
klgentle/lc_python
refs/heads/master
/vs_code/split_dept.py
import shutil, os import openpyxl class SplitDept(object): def __init__(self,sheet_name): self.from_path = "/mnt/e/yx_walk/report_develop/report_dept" self.from_file = "ods_reports.xlsx" self.to_file = "ods_reports_out.xlsx" self.data_row = [] self.data_list = [] self.sheet_name = sheet_name def readData(self): wb = openpyxl.load_workbook(os.path.join(self.from_path, self.from_file)) #sheet = wb.active sheet = wb.get_sheet_by_name(self.sheet_name) dept_name = "" # range from index to change for row in range(7, sheet.max_row + 1): name = sheet["A" + str(row)].value if not name: #pass continue # continue for blank #else: #dept_name = name #data_row = [sheet[chr(i + ord("A")) + str(row)].value for i in range(0, 2)] #dept_name = sheet["B" + str(row)].value #dept_name = dept_name.split(' - ')[0] #if dept_name.isnumeric(): # dept_name = "X"+dept_name #data_row = [name, dept_name] #print(f"data_row:{data_row}") data_row = [sheet["B" + str(row)].value, sheet["E" + str(row)].value] self.data_row.append(data_row) def saveData(self): file_path_name = os.path.join(self.from_path, self.to_file) wb = openpyxl.load_workbook(file_path_name) #sheet = wb.active sheet = wb.create_sheet(self.sheet_name) #sheet = wb.get_sheet_by_name(self.sheet_name) for row in self.data_list: #print(f"row:{row}") sheet.append(row) wb.save(filename=file_path_name) def splitData(self): for row in self.data_row: rpt_id = row[0] rpt_dept = "" if len(row) == 1: self.data_list.append([rpt_dept, rpt_id]) else: if row[1] and row[1].find(",") > -1: rpt_dept_list = row[1].split(", ") # 中文标点 for rpt_dept in rpt_dept_list: self.data_list.append([rpt_dept, rpt_id]) else: rpt_dept = row[1] self.data_list.append([rpt_dept, rpt_id]) if __name__ == "__main__": sheet_name = "PMO Report-Recipient Mapping" a = SplitDept(sheet_name) a.readData() a.splitData() a.saveData() print(f"All done!")
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,932
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/tree/p0889_Construct_Binary_Tree_from_Preorder_and_Postorder_Traversal.py
""" 889. Construct Binary Tree from Preorder and Postorder Traversal Medium Return any binary tree that matches the given preorder and postorder traversals. Values in the traversals pre and post are distinct positive integers. Example 1: Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1] Output: [1,2,3,4,5,6,7] Note: 1 <= pre.length == post.length <= 30 pre[] and post[] are both permutations of 1, 2, ..., pre.length. It is guaranteed an answer exists. If there exists multiple answers, you can return any of them. """ class Solution: """ A preorder traversal is: (root node) (preorder of left branch) (preorder of right branch) While a postorder traversal is: (postorder of left branch) (postorder of right branch) (root node) """ def constructFromPrePost(self, pre: List[int], post: List[int]) -> TreeNode: if not pre: return None root = TreeNode(pre[0]) # 防止返回多余的空结点 if len(pre) == 1: return root # 根据左子树的根结点确定左边子树结点树,然后分左右 len_of_left = post.index(pre[1]) + 1 # root, left, right root.left = self.constructFromPrePost(pre[1:len_of_left+1], post[:len_of_left]) root.right = self.constructFromPrePost(pre[len_of_left+1:], post[len_of_left:-1]) return root
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,933
klgentle/lc_python
refs/heads/master
/encode/encrypt.py
from Crypto.Cipher import DES key = b'abcdefgh' # 密钥 8位或16位,必须为bytes def pad(text): """ # 加密函数,如果text不是8的倍数【加密文本text必须为8的倍数!】,那就补足为8的倍数 :param text: :return: """ while len(text) % 8 != 0: text += ' ' return text des = DES.new(key, DES.MODE_ECB) # 创建一个DES实例 #text = 'Python rocks!' text = input('Please input pactera password: ') padded_text = pad(text) encrypted_text = des.encrypt(padded_text.encode('utf-8')) # 加密 print(encrypted_text) with open("pactera_passwd_encrpt.txt","wb") as f: #f.write(str(encrypted_text)) f.write(encrypted_text)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,934
klgentle/lc_python
refs/heads/master
/tests/test_os_sep.py
import os def test_change_path_sep(path): if path.find("\\") > -1 and os.sep != "\\": path = path.replace("\\", os.sep) elif path.find("/") > -1 and os.sep != "/": path = path.replace("/", os.sep) return path if __name__== "__main__": path1 = "1000_编辑区/1300_编码/1301_ODSDB/RPTUSER/05Procedures" print(test_change_path_sep(path1)) path2 = r"1000_编辑区\1300_编码\1370_水晶报表\CIF" print(test_change_path_sep(path2))
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,935
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/array/p1011_Capacity_To_Ship_Packages_Within_D_Days.py
""" 1011. Capacity To Ship Packages Within D Days Medium A conveyor belt has packages that must be shipped from one port to another within D days. The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within D days. Example 1: Input: weights = [1,2,3,4,5,6,7,8,9,10], D = 5 Output: 15 Explanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this: 1st day: 1, 2, 3, 4, 5 2nd day: 6, 7 3rd day: 8 4th day: 9 5th day: 10 Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed. Example 2: Input: weights = [3,2,2,4,1,4], D = 3 Output: 6 Explanation: A ship capacity of 6 is the minimum to ship all the packages in 3 days like this: 1st day: 3, 2 2nd day: 2, 4 3rd day: 1, 4 Example 3: Input: weights = [1,2,3,1,1], D = 4 Output: 3 Explanation: 1st day: 1 2nd day: 2 3rd day: 3 4th day: 1, 1 """ class Solution: def shipWithinDays(self, weights: List[int], D: int) -> int: maxCapa = sum(weights) # 用二分法进行优化 left = max(weights) while left < maxCapa: c_mid = int((left + maxCapa) / 2) if self.canShip(weights, D, c_mid): maxCapa = c_mid else: left = c_mid + 1 return left def canShip(self, w, D, c): """ 此函数思想挺好,每天重新分配容量,最终看w[i]是否分配完。 """ i = 0 # 注意取值的边界条件 for day in range(D): maxC = c while maxC - w[i] >= 0: maxC -= w[i] i += 1 if i == len(w): return True
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,936
klgentle/lc_python
refs/heads/master
/tests/unittest_demo.py
import unittest class TestDict(unittest.TestCase): def setUp(self): print('setUp...') def test_some_case(self): pass def tearDown(self): print('tearDown...') if __name__ == '__main__': unittest.main()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,937
klgentle/lc_python
refs/heads/master
/base_practice/print_prime.py
def main(): for c in range(1,100): if is_prime(c): print(c) def is_prime(v): if v<2: return False elif v==2: return True else: i=2 while i<v: if((v%i)==0): return False else: i+=1 return True main()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,938
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/tree/P0106_Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.py
""" Given inorder and postorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. For example, given inorder = [9,3,15,20,7] postorder = [9,15,7,20,3] Return the following binary tree: 3 / \ 9 20 / \ 15 7 """ class Solution: def buildTree(self, inorder, postorder): if not inorder or not postorder: return None root = TreeNode(postorder.pop()) inorderIndex = inorder.index(root.val) # Line A # 为什么先计算右边的就可以出来?先左边的就不行 # 因为右结点离根结点近(就是因为左右顺序搞错,浪费了一下午时间) root.right = self.buildTree(inorder[inorderIndex + 1 :], postorder) # Line B root.left = self.buildTree(inorder[:inorderIndex], postorder) # Line C return root
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,939
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/array/p0710_Random_Pick_with_Blacklist.py
""" 710. Random Pick with Blacklist Hard Given a blacklist B containing unique integers from [0, N), write a function to return a uniform random integer from [0, N) which is NOT in B. Optimize it such that it minimizes the call to system’s Math.random(). Note: 1 <= N <= 1000000000 0 <= B.length < min(100000, N) [0, N) does NOT include N. See interval notation. """ from random import randint class Solution: def __init__(self, N: int, blacklist: List[int]): # new list:[0, white_len), [white_len, N). Focus on the last list self.white_len = N - len(blacklist) # new list 中小于white_len的blacklist会与大于white_len的非blacklist相对应 keyToMove = [x for x in blacklist if x < self.white_len] valueToMatch = [x for x in range(self.white_len, N) if x not in blacklist] self.mapping = dict(zip(keyToMove, valueToMatch)) def pick(self) -> int: i = randint(0, self.white_len-1) return self.mapping.get(i, i) # Your Solution object will be instantiated and called as such: # obj = Solution(N, blacklist) # param_1 = obj.pick()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,940
klgentle/lc_python
refs/heads/master
/base_practice/rename_file_to_lower.py
import os # import sh def filename_to_lower(file_dir=os.getcwd()): # can't rename filename to filename.lower with os.rename() for filename in os.listdir(file_dir): if filename.startswith("P_"): old_src = os.path.join(file_dir, filename) tmp_src = os.path.join(file_dir, filename.lower() + " ") dst_name = os.path.join(file_dir, filename.lower()) # add blank os.rename(old_src, tmp_src) # delete blank os.rename(tmp_src, dst_name) if __name__ == "__main__": filename_to_lower()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,941
klgentle/lc_python
refs/heads/master
/base_practice/create_foler_and_file_from_list.py
import os from pprint import pprint PATH = "/mnt/d/code_test/lc_python/leet_code/top_interview_questions" # PATH = "D\\code_test\\lc_python\\leet_code\\top_interview_questions" def open_file(file_name: str) -> list: file_name_list = [] with open(file_name, "r") as file: for line in file.readlines(): id, problem_name, difficulty = line.strip().split("\t") id = id.zfill(4) difficulty = difficulty + "_Case" problem_name = problem_name.strip() file_name_list.append([id, problem_name, difficulty]) return file_name_list def make_path_of_all(): for folder_name in ("Easy_Case", "Medium_Case", "Hard_Case"): new_path = os.path.join(PATH, folder_name) if not os.path.exists(new_path): os.makedirs(new_path) def create_folder_and_file_from_list(file_name_list): for file_and_folder in file_name_list: file_name = file_and_folder[0] + "_" + file_and_folder[1] + ".py" folder_name = file_and_folder[2] new_file = os.path.join(PATH, folder_name, file_name) f = open(new_file, "w") f.close() if __name__ == "__main__": make_path_of_all() file_name = os.path.join(PATH, "list.txt") file_list = open_file(file_name) create_folder_and_file_from_list(file_list) print("Done!")
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,942
klgentle/lc_python
refs/heads/master
/leet_code/medium_case/0091_Decode_Ways.py
from pysnooper import snoop class Solution: """ s = '226' set[0] = 2 set[1] = [[2,2],[22]] set[2] = [[2,26],[22,6],[2,2,6]] """ @snoop() def numDecodings(self, s: str) -> int: if not s or s.startswith('0'): return 0 dp = [0] * len(s) dp[0] = 1 for i in range(1, len(s)): if s[i] != '0': dp[i] += dp[i - 1] if s[i - 1] != '0' and int(s[i - 1:i + 1]) <= 26: tmp = dp[i - 2] if i - 2 >= 0 else 1 dp[i] += tmp return dp[-1] # todo return multiply of len of all subset if __name__ == "__main__": a = Solution() s = "4757562545844617494555774581341211511296816786586787755257741178599337186486723247528324612117156948" a.numDecodings(s)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,943
klgentle/lc_python
refs/heads/master
/leet_code/easy_case/lengthOfLastWord.py
class Solution: def lengthOfLastWord(self, s: str) -> int: lst = s.strip().split(" ") print(lst) return len(lst[-1]) if bool(lst) else 0 if __name__ == "__main__": a = Solution() a.lengthOfLastWord("a ")
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,944
klgentle/lc_python
refs/heads/master
/tests/test_re_match.py
import unittest import re class TestReMatch(unittest.TestCase): def test_some_case(self): s = """<img ' 'onload="this.parentNode.parentNode.classList.remove(\'placeholder\')" ' 'class="" alt="" ' 'data-src="https://images.weserv.nl/?url=https://i.imgur.com/kewGjoO.jpg#vwid=860&vhei=1290" ' 'src="https://images.weserv.nl/?url=https://i.imgur.com/kewGjoO.jpg#vwid=860&vhei=1290"></a></figure><br><figure ' 'class="placeholder size-parsed" style="flex-grow: 33.884948778566" ><a ' 'style="padding-top: 147.55813953488%" no-pjax data-fancybox="gallery" ' 'data-caption="" ' 'href="https://images.weserv.nl/?url=https://i.imgur.com/4bLkVbY.jpg#vwid=860&vhei=1269"> <img ' 'onload="this.parentNode.parentNode.classList.remove(\'placeholder\')" ' 'class="" alt="" ' 'data-src="https://images.weserv.nl/?url=https://i.imgur.com/4bLkVbY.jpg#vwid=860&vhei=1269" ' 'src="https://images.weserv.nl/?url=https://i.imgur.com/4bLkVbY.jpg#vwid=860&vhei=1269"></a></figure><br><figure ' 'class="placeholder size-parsed" style="flex-grow: 37.423846823325" ><a ' 'style="padding-top: 133.60465116279%" no-pjax data-fancybox="gallery" ' 'data-caption="" ' 'href="https://images.weserv.nl/?url=https://i.imgur.com/0UAtXIp.jpg#vwid=860&vhei=1149"> """ p = re.compile( #"https://images.weserv.nl/\?url=https://i.imgur.com/\w*.jpg" "http.*\#vwid" ) tempList = re.findall(p, s) print(tempList) if __name__ == '__main__': unittest.main()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,945
klgentle/lc_python
refs/heads/master
/GUI/window_with_input_and_button.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # author:洪卫 import tkinter as tk # 使用Tkinter前需要先导入 # 第1步,实例化object,建立窗口window window = tk.Tk() # 第2步,给窗口的可视化起名字 window.title("My Window") # 第3步,设定窗口的大小(长 * 宽) window.geometry("800x300") # 这里的乘是小x # 第4步,在图形界面上设定输入框控件entry框并放置 lbl = tk.Label(window, text="请输入something") lbl.grid(column=0, row=0) # lbl.pack() e = tk.Entry(window, show=None) # 显示成明文形式 e.grid(column=1, row=0) # e.pack() # 第5步,定义两个触发事件时的函数insert_point和insert_end(注意:因为Python的执行顺序是从上往下,所以函数一定要放在按钮的上面) def insert_point(): # 在鼠标焦点处插入输入内容 var = e.get() t.insert("insert", var) def insert_end(): # 在文本框内容最后接着插入输入内容 var = e.get() t.insert("end", var) # 第6步,创建并放置两个按钮分别触发两种情况 b1 = tk.Button(window, text="insert point", width=10, height=2, command=insert_point) # b1.pack() b1.grid(column=0, row=1) b2 = tk.Button(window, text="insert end", width=10, height=2, command=insert_end) # b2.pack() b2.grid(column=1, row=1) # 第7步,创建并放置一个多行文本框text用以显示,指定height=3为文本框是三个字符高度 t = tk.Text(window, height=3, width=50) # t.pack() # t.grid(row=3) t.place(x=0, y=100) # 第8步,主窗口循环显示 window.mainloop()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,946
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/tree/p0112_Path_Sum.py
""" 112. Path Sum Easy Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. A leaf is a node with no children. Example 1: Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 Output: true Example 2: Input: root = [1,2,3], targetSum = 5 Output: false Example 3: Input: root = [1,2], targetSum = 0 Output: false """ class Solution: def hasPathSum(self, root: TreeNode, targetSum: int) -> bool: if not root: return False if not root.left and not root.right: if targetSum == root.val: return True return False targetSum = targetSum - root.val left_has = False right_has = False if root.left: left_has = self.hasPathSum(root.left, targetSum) if root.right: right_has = self.hasPathSum(root.right, targetSum) return left_has or right_has
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,947
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/linked_list/p0382_Linked_List_Random_Node.py
""" 382. Linked List Random Node Medium Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen. Example 1: Input ["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"] [[[1, 2, 3]], [], [], [], [], []] Output [null, 1, 3, 2, 2, 3] """ from random import randint # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def __init__(self, head: ListNode): """ @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. """ self._head = head def getRandom(self) -> int: """ Returns a random node's value. 第 i 个元素被选择的概率是 1/i,第 i+1 次不被替换的概率是 1 - 1/(i+1),以此类推, 相乘就是第 i 个元素最终被选中的概率,就是 1/n。 """ result, node, index = self._head, self._head.next, 1 while node: if randint(0, index) == 0: result = node index += 1 node = node.next return result.val # Your Solution object will be instantiated and called as such: # obj = Solution(head) # param_1 = obj.getRandom()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,948
klgentle/lc_python
refs/heads/master
/automatic_office/ExtractTheReferencedFile.py
import os import shutil import sys import logging import yaml #logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s") class ExtractTheReferencedFile(object): def __init__(self, versionDate): self.versionDate = versionDate self.getPath() self.fileList = [] def getPath(self): logging.debug(os.getcwd()) with open(os.path.join("bin", "config.yaml"), "r") as config: cfg = yaml.safe_load(config) logging.debug(cfg) self.systemName = cfg.get('systemName') self.inputDir = cfg.get('inputDir').format(self.versionDate) self.outputDir = cfg.get('outputDir').format(self.systemName,self.versionDate) self.sourceDir = cfg.get('sourceDir') def isPathExists(self): if not os.path.exists(self.sourceDir): logging.error("sourceDir not exists") return False if not os.path.exists(self.inputDir): logging.error("inputDir[%s] not exists" % self.inputDir) return False if not os.path.exists(self.outputDir): logging.info("outputDir[%s] not exists" % self.outputDir) os.makedirs(self.outputDir, exist_ok=True) logging.info("outputDir 已创建!") return True def referencedLineFormat(self, line): line = line.strip('\n') line = line.strip() line = line.strip(';') return line.replace('@..\\..\\', '') def getListFiles(self): for folderName, subfolders, filenames in os.walk(self.inputDir): for filename in filenames: logging.debug(filename) if filename.endswith(".ktr"): continue with open(os.path.join(self.inputDir,filename), "r", encoding='gbk', errors='ignore') as f: for line in f.readlines(): if line[0] == "@": self.fileList.append(self.referencedLineFormat(line)) logging.debug(self.fileList) def copyFile(self, fromDir, toDir): if not os.path.exists(toDir): os.makedirs(toDir, exist_ok=True) try: shutil.copy(fromDir, toDir) except FileNotFoundError: logging.error("[%s] not find" % fromDir) def copyAllFiles(self): if self.isPathExists(): self.getListFiles() for filename in self.fileList: logging.debug(filename) file_and_dir_list = filename.split("\\") target_path = os.path.join(self.outputDir, "\\".join(file_and_dir_list[:-1])) from_path = os.path.join(self.sourceDir, filename) self.copyFile(from_path, target_path) logging.info("python 取文件完成") if __name__ == "__main__": if len(sys.argv) < 2: print("请输入versionDate") sys.exit(1) if len(sys.argv[1]) != 11: print("versionDate格式不符", sys.argv[1]) sys.exit(1) versionDate = sys.argv[1] o = ExtractTheReferencedFile(versionDate) o.copyAllFiles()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,949
klgentle/lc_python
refs/heads/master
/leet_code/easy_case/rob_ans2.py
# coding:utf8 #import pysnooper class Solution(object): # debug here #@pysnooper.snoop() def rob(self, nums: list) -> int: """ :type nums: List[int] # 这是一个动态规划问题 """ l = len(nums) opt = [0, 0] opt.extend([None] * (l - 2)) if not nums: return 0 if l == 1: return nums[0] opt[0], opt[1] = nums[0], max(nums[0], nums[1]) for i in range(2, l): opt[i] = max(opt[i - 1], opt[i - 2] + nums[i]) return opt[-1] if __name__ == "__main__": a = Solution() lst1 = [1, 2, 3, 1] lst2 = [2, 1, 1, 2] lst3 = [1, 1, 1, 2] # a.rob(lst1) a.rob(lst3)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,950
klgentle/lc_python
refs/heads/master
/data_structure/knap_rec.py
""" 背包问题 一个背包,可以装下weight的重量. 现在一个集合S, 里面有多个物品,请写一个程序,判断是否存在若干件个物品,刚好重量为weight -----提示: 考虑最后一件物品 """ def knap_rec(weight, wlist, n): if weight == 0: return True if weight < 0 or (weight > 0 and n < 1): return False # 考虑第n件物品 if knap_rec(weight - wlist[n - 1], wlist, n - 1): print(f"Item {n}: {wlist[n-1]}") return True # 不考虑第n件物品 if knap_rec(weight, wlist, n - 1): return True else: # 思考这个else 可以不可以去掉? 好像可以 return False
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,951
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/linked_list/p0025._Reverse_Nodes_in_k-Group.py
""" 25. Reverse Nodes in k-Group Hard Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. Follow up: Could you solve the problem in O(1) extra memory space? You may not alter the values in the list's nodes, only nodes itself may be changed. Example 1: Input: head = [1,2,3,4,5], k = 2 Output: [2,1,4,3,5] """ # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: if not head: return a, b = head, head for i in range(0,k): # base case if not b: return head b = b.next newhead = self.reverse(a, b) a.next = self.reverseKGroup(b, k) return newhead def reverse(self, a: ListNode, b: ListNode) -> ListNode: pre = None while a != b: curr = a # 往下走一个 a = a.next curr.next = pre pre = curr return pre
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,952
klgentle/lc_python
refs/heads/master
/vs_code/list_file.py
import os import time def list_file(path: str, file_name: str, path2: str): to_file = open(file_name, "w") date_str = time.strftime("%Y%m%d", time.localtime()) to_path = f"D:\jdong\\beta\\{date_str}beta\\{path2}" for f in os.listdir(path): s = f"@@{to_path}\{f};\n" to_file.write(s) to_file.write("commit;\n") to_file.close() #print("list file done!") def create_file_list(list_file: str): file_list = [] with open(list_file,"r") as file: file_list = file.read().strip().split('\n') def list_file_of_path(file_path: str): to_file = open(os.path.join(file_path, "list_pro.sql"), "w") to_file.write(f"set define off\nspool.log\n\n") for proc_name in os.listdir(path): if pro_name == "list_pro.sql": continue file_name = proc_name name_without_type = proc_name[:-4] s = f"prompt\nprompt {name_without_type}\n@@{file_name}\nprompt\nprompt ==============================\nprompt\n" to_file.write(s) to_file.write("\nspool off\ncommit;\n") to_file.close() if __name__ == "__main__": path = r"/mnt/e/yx_walk/report_develop/view_to_replace/cif_to_check" list_file_of_path(path)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,953
klgentle/lc_python
refs/heads/master
/base_practice/GolfScoreWriter.py
def main(): """ 代码修改记录: 1、删除count=0, count+=1不需要赋值,count是变量,它的值在range里 2、golf.file改为golf_file 3、删除所有的,sep='', sep在的话,无法input 4、input 修改,不能有多个, 5、wirte修改为write,单词写错 """ num=int(input("Enter number of players:")) golf_file=open('golf.txt','w') for count in range(1,num+1): name=input("Enter name of player number {}:".format(count)) score=input(f"Enter score of player number {count}:") golf_file.write(str(name)+"\n") golf_file.write(str(score)+"\n") golf_file.close() main()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,954
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/tree/p0429_N-ary_Tree_Level_Order_Traversal.py
""" Given an n-ary tree, return the level order traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples). Example 1: Input: root = [1,null,3,2,4,null,5,6] Output: [[1],[3,2,4],[5,6]] """ """ # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def levelOrder(self, root: "Node") -> List[List[int]]: q, result = deque(), [] if root: q.append(root) while q: level = [] for _ in range(len(q)): node = q.popleft() level.append(node.val) for child in node.children: if child: q.append(child) result.append(level) return result
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,955
klgentle/lc_python
refs/heads/master
/leet_code/medium_case/0238_Product_of_Array_Except_Self.py
class Solution: """ List set value is faster than append value """ def productExceptSelf(self, nums: list) -> list: length = len(nums) left = [1]*length right = [1]*length ret = [1]*length for i in range(1,length): left[i] = left[i-1] * nums[i-1] for i in range(length-1, 0, -1): right[i-1] = right[i]*nums[i] for i in range(length): ret[i] = left[i]*right[i] return ret
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,956
klgentle/lc_python
refs/heads/master
/data_structure/c9_3_bubble_sort.py
def bubble_sort(lst): for i in range(len(lst)): #一次完整的扫描(比较和交换)能保证把一个最大的元素移到到未排序部分的最后 for j in range(1, len(lst) - i): if lst[j - 1].key > lst[j].key: lst[j - 1], lst[j] = lst[j], lst[j - 1] def bubble_sort2(lst): """改进:如果在一次扫描中没有遇到逆序,说明排序工作已经完成,可以提前结束了""" for i in range(len(lst)): found = False #一次完整的扫描(比较和交换)能保证把一个最大的元素移到到未排序部分的最后 for j in range(1, len(lst) - i): if lst[j - 1].key > lst[j].key: lst[j - 1], lst[j] = lst[j], lst[j - 1] found = True if not found: break
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,957
klgentle/lc_python
refs/heads/master
/leet_code/medium_case/0287_Find_the_Duplicate_Number.py
class Solution(object): """refer to http://bookshadow.com/weblog/2015/09/28/leetcode-find-duplicate-number/""" def findDuplicate(self, nums): # The "tortoise and hare" step. We start at the end of the array and try # to find an intersection point in the cycle. slow = 0 fast = 0 # Keep advancing 'slow' by one step and 'fast' by two steps until they # meet inside the loop. while True: slow = nums[slow] fast = nums[nums[fast]] if slow == fast: break # Start up another pointer from the end of the array and march it forward # until it hits the pointer inside the array. finder = 0 while True: slow = nums[slow] finder = nums[finder] # If the two hit, the intersection index is the duplicate element. if slow == finder: return slow
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,958
klgentle/lc_python
refs/heads/master
/automatic_office/CreateWeekReport.py
import datetime import pysnooper import pprint import os import sys import shutil import docx import logging import openpyxl # 绝对路径的import sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../") logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s") from automatic_office.CheckInForm import CheckInForm from automatic_office.DealInterval import DealInterval class CreateWeekReport(object): """ 根据工作日期,生成周报模板 """ def __init__(self, year_month: str): if len(year_month) != 6: print("Please input year_month with format: YYYYMM!") sys.exit(1) self.year_month = year_month self.interval = DealInterval() self.__from_dir = os.path.join( os.path.dirname(os.path.abspath(__file__)) + "/../", "automatic_office", "doc_file", ) self.__target_dir = self.get_target_dir() self.from_word = "创兴银行香港ODS项目周报_董坚_fromEndStr.docx" self.from_excel = "工作周报_fromEndStr.xlsx" def get_from_dir(self): return self.__from_dir def get_target_dir(self): short_year = self.year_month[2:4] month = self.year_month[4:] next_month = str(int(month) +1).zfill(2) print("next_month:", next_month) target_dir = os.path.join(self.__from_dir, f"文思周报【{short_year}{month}-{short_year}{next_month}】", "董坚") if not os.path.exists(target_dir): os.makedirs(target_dir, exist_ok=True) return target_dir def copy_file(self, from_file_name, target_file_name: str): logging.info("创建文件:%s" % target_file_name) shutil.copy( os.path.join(self.__from_dir, from_file_name), os.path.join(self.__target_dir, target_file_name), ) @staticmethod def replace_date_str(content: str, date_name: str, date_str: str) -> str: if date_name in content: logging.debug("替换文本[%s]为[%s]" % (date_name, date_str)) content = content.replace(date_name, date_str) return content def replace_all_str(self, text: str, date_tuple: tuple, date_tuple2=()) -> str: text = self.replace_date_str( text, "fromEndStr", self.interval.get_from_end_str(date_tuple) ) text = self.replace_date_str( text, "fromDate", self.interval.get_from_date(date_tuple) ) text = self.replace_date_str( text, "endDate", self.interval.get_end_date(date_tuple) ) if date_tuple2: text = self.replace_date_str( text, "nextFD", self.interval.get_from_date(date_tuple2) ) text = self.replace_date_str( text, "nextND", self.interval.get_end_date(date_tuple2) ) return text def check_word_change(self, file_name, date_tuple: tuple): logging.info("replace word") word_file = os.path.join(self.__target_dir, file_name) document = docx.Document(word_file) for para in document.paragraphs: for i, run in enumerate(para.runs): run.text = self.replace_all_str(run.text, date_tuple) document.save(word_file) def check_excel_change(self, file_name, date_tuple: tuple, date_tuple2): logging.info("replace excel") file_path = os.path.join(self.__target_dir, file_name) wb = openpyxl.load_workbook(file_path) sheet = wb.active for row in range(1, sheet.max_row + 1): for col in range(1, sheet.max_column + 1): if sheet.cell(row, col).value in ("fromEndStr", "fromDate", "endDate", "nextFD", "nextND"): logging.debug("excel value:[%s]" % sheet.cell(row, col).value) # 替换单元格的值 sheet.cell(row, col).value = self.replace_all_str( sheet.cell(row, col).value, date_tuple, date_tuple2 ) wb.save(file_path) def create_week_report(self): weekdays = CheckInForm(self.year_month).get_all_work_date() logging.info("开始生成周报...") date_tuples = self.interval.get_all_weekday_interval(weekdays, []) for i, date_tuple in enumerate(date_tuples): from_end_str = self.interval.get_from_end_str(date_tuple) word_file_name = self.from_word.replace("fromEndStr", from_end_str) # copy word file self.copy_file(self.from_word, word_file_name) # replace content self.check_word_change(word_file_name, date_tuple) excel_file_name = self.from_excel.replace("fromEndStr", from_end_str) # copy excel file self.copy_file(self.from_excel, excel_file_name) date_tuple2 = () if i+1 < len(date_tuples): date_tuple2 = date_tuples[i+1] else: date_tuple2 = (date_tuple[0] + datetime.timedelta(7), date_tuple[1] + datetime.timedelta(7)) self.check_excel_change(excel_file_name, date_tuple, date_tuple2) logging.info("周报已生成!") if __name__ == "__main__": if len(sys.argv) <= 1: logging.info("Please input year_moth(YYYYMM)") sys.exit(1) obj = CreateWeekReport(sys.argv[1]) obj.create_week_report()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,959
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/tree/p0700_Search_in_a_Binary_Search_Tree.py
""" 700. Search in a Binary Search Tree You are given the root of a binary search tree (BST) and an integer val. Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null. Example 1: Input: root = [4,2,7,1,3], val = 2 Output: [2,1,3] """ class Solution: def searchBST(self, root: TreeNode, val: int) -> TreeNode: if not root: return root if root.val == val: return root """ elif root.val > val: return self.searchBST(root.left, val) elif root.val < val: return self.searchBST(root.right, val) """ return self.searchBST(root.left, val) or self.searchBST(root.right, val)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,960
klgentle/lc_python
refs/heads/master
/leet_code/medium_case/findNumberOfLIS_673_v1.py
#! python3 from collections import Counter from pprint import pprint class Solution: def findNumberOfLIS(self, nums) -> int: # def findNumberOfLIS(self, nums: List[int]) -> int: # 给定一个未排序的整数数组,找到最长递增子序列的个数。 """ to looking for increase sub set, conside each point of the list, for each point create one increase list, if one element is large than it append it at end, if min than it then add it before. """ # questoins: # how to put element in the first position of one list? [1] + [2,3] = [1,2,3](lst = nums[i] + lst) # special cases1 (equal) [2,2,2]: nums_len = len(nums) if nums_len == 0: return 0 elif nums_len == 1: return 1 if len(set(nums)) == 1: return len(nums) # special case2 (decrease) [5,4,3,2,1] TODO num2 = [] # num2 like [[],[],...,[]] # initialize for i in range(0, len(nums)): num2.append([]) for j in range(0, len(nums)): num2[j].append(nums[j]) # print('j: ', j) # the before list for i in range(j - 1, -1, -1): # print('i: ', i) # [1,3,5,4,7,...,5,8,9,100] if nums[i] < nums[j] and nums[i] < num2[j][0]: num2[j] = [nums[i]] + num2[j] # the behead list for i in range(j + 1, len(nums)): if nums[i] > nums[j] and nums[i] > num2[j][-1]: num2[j].append(nums[i]) # print('end i, num2: ', num2) print("num2 _________________:") pprint(num2) target_list = [] for i in num2: if i not in target_list: target_list.append(i) print("target_list: ", target_list) target_len_list = [len(i) for i in target_list] max_len = max(target_len_list) count = Counter(target_len_list).most_common() # only on when duplicate value in the max_len sub then count duplicate times: TODO target_list_long = [] for i in target_list: if len(i) == max_len: target_list_long.append(i) pop_list = [] # [i[0] for i in target_list_long] # to deal with duplicate value to_add = 0 # get the index of dulplicate element, compare the response num2[i], # if num2[i] is the same then add 1 # [[1,2],[5,6,7]] # [(1,112),(4,112)] # dulp_list = [] dulp_value_list = [] nums_unique = [] for e in nums: if e not in nums_unique: nums_unique.append(e) else: # filter the pop_list elements if e not in pop_list and e in target_list_long[0]: dulp_value_list.append(e) dulp_value_list = list(set(dulp_value_list)) print("dulp_value_list:", dulp_value_list) dulp_ind = [] for i in dulp_value_list: sign_value_list = [] for j in range(0, len(nums)): if nums[j] == i: sign_value_list.append(j) print("sign_value_list: ", sign_value_list) dulp_ind.append(sign_value_list) print("dulp_ind: ", dulp_ind) for item in dulp_ind: print("item: ", item) for i in item: if num2[i] not in target_list_long: continue for j in item: print("num2[%s]:" % i, num2[i]) print("num2[%s]:" % j, num2[j]) # print('to_add:', to_add) if i < j and num2[i] == num2[j]: to_add += 1 print("to_add:", to_add) target = dict(count).get(max_len) print("target: ", target) # to_add = 0 # part 2 deal_.... return target + to_add
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,961
klgentle/lc_python
refs/heads/master
/base_practice/ph.py
print(f"please input ph value:") ph=float(input()) print(f"input:{ph}") if ph<7.0: neutral=0;base=0;acid=1 elif ph>7.0: neutral=0;base=1;acid=0 elif ph==7.0: neutral=1;base=0;acid=0 print(f"neutral={neutral};base={base};acid={acid}")
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,962
klgentle/lc_python
refs/heads/master
/leet_code/easy_case/numberOfBoomerangs_ref.py
class Solution: """ 执行用时: 1624 ms, 在Number of Boomerangs的Python3提交中击败了79.56% 的用户 """ def numberOfBoomerangs(self, points): """ 降维 看似三个点之间比较,其实只要比两个点 计算其他点到当前点的距离,如果相同距离的点有2个以上则满足(有An2种可能) :type points: List[List[int]] :rtype: int """ n = len(points) sum1 = 0 for i in range(n): dic = {} for j in range(n): # 排除这个点本身 if j != i: dis = self.distance(points[i], points[j]) if dis not in dic: dic[dis] = 1 else: dic[dis] += 1 # print(dic) for value in dic.values(): if value >= 2: sum1 += int(value * (value - 1)) return sum1 def distance(self, point1, point2): return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,963
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/tree/p0662_Maximum_Width_of_Binary_Tree.py
""" 662. Maximum Width of Binary Tree Medium Given a binary tree, write a function to get the maximum width of the given tree. The maximum width of a tree is the maximum width among all levels. The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation. It is guaranteed that the answer will in the range of 32-bit signed integer. Example 1: Input: 1 / \ 3 2 / \ \ 5 3 9 Output: 4 Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9). Example 2: Input: 1 / 3 / \ 5 3 Output: 2 Explanation: The maximum width existing in the third level with the length 2 (5,3). """ class Solution: def widthOfBinaryTree(self, root: TreeNode) -> int: queue = [(root, 0, 0)] cur_depth = left = ans = 0 for node, depth, pos in queue: #print(f"depth:{depth}") if node: # set position of left is 2 * (root position), rigth is 2 * pos +1 queue.append((node.left, depth+1, pos * 2)) queue.append((node.right, depth+1, pos * 2 +1)) if cur_depth != depth: cur_depth = depth left = pos # R - L + 1 = length of level ans = max(ans, pos - left +1) return ans
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,964
klgentle/lc_python
refs/heads/master
/leet_code/medium_case/p0535_Encode_and_Decode_TinyURL.py
class Codec: def __init__(self): self.hashDict = {} self.tinyPrefix = 'http://tinyurl.com/' def encode(self, longUrl: str) -> str: """Use hash method to encodes a URL to a shortened URL. """ shortUrl = self.tinyPrefix + str(hash(longUrl)) self.hashDict[shortUrl] = longUrl return shortUrl def decode(self, shortUrl: str) -> str: """Decodes a shortened URL to its original URL. """ return self.hashDict.get(shortUrl) # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.decode(codec.encode(url))
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,965
klgentle/lc_python
refs/heads/master
/wechat/tm_01_birthday.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/9/26 14:29 # @Author : T.M. # @File : tm_01_定时发送生日祝福.py # @Software: PyCharm """ 1.扫描学生信息表,根据当天日期,找到当天过生日同学的姓名(微信昵称) 2.登录微信接口,发送消息 """ import time import pandas as pd from wxpy import * def get_birthday_student_list(): # 1.读取学生信息表 df = pd.read_csv("./student_info.csv") # 2.获取当日日期 now_time = time.strftime("%Y-%m-%d", time.localtime()) # print(now_time) # 2019-09-26 wx_list = [] # 3.遍历表格,筛选出当天过生日的同学 for index, row in df.iterrows(): # 找到满足条件的同学,返回一个列表 # 当天过生日的同学 if now_time == row["birthday"]: # print(row['wx'], row['birthday']) wx_list.append(row["wx"]) return wx_list def send_message(wx): # 向每一位过生日的同学发送祝福 try: # 1.对方的微信名称 my_friend = bot.friends().search(wx)[0] # 2.定制消息 message = "生日快乐!" # 发送消息给对方 my_friend.send(message) except: # 出问题时,发送信息到文件传输助手 bot.file_helper.send(u"守护女友出问题了,赶紧去看看咋回事~") if __name__ == "__main__": # 1.获取过生日的学生名单 wx_list = get_birthday_student_list() # 2.利用 wxpy 模块,初始化机器人对象 bot = Bot() # 3.向每一位过生日的同学发送祝福 for wx in wx_list: send_message(wx)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,966
klgentle/lc_python
refs/heads/master
/tests/test_raise_error.py
inputValue=input("please input a int data :") if inputValue != '1': raise ValueError("not 1") #raise Exception("not 1") else: print(inputValue)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,967
klgentle/lc_python
refs/heads/master
/leet_code/easy_case/isValid_answer.py
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ if len(s) % 2 != 0: return False lb = {"(": ")", "[": "]", "{": "}"} queue = [] for x in s: if x in lb: queue.append(x) else: if len(queue) == 0: return False top = queue.pop() if lb[top] != x: return False return len(queue) == 0
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,968
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/linked_list/p0092_Reverse_Linked_List_II.py
""" 92. Reverse Linked List II Medium Reverse a linked list from position m to n. Do it in one-pass. Note: 1 ≤ m ≤ n ≤ length of list. Example: Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL """ # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def __init__(self): self.successor = ListNode() def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: if m ==1: return self.reverseN(head, n) # 指针往前移 head.next = self.reverseBetween(head.next, m-1, n-1) return head def reverseN(self, head: ListNode, n: int) -> ListNode: if n == 1: self.successor = head.next return head # 递归反转 last = self.reverseN(head.next, n-1) head.next.next = head head.next = self.successor return last
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,969
klgentle/lc_python
refs/heads/master
/database/AutoViewReplace.py
import os import sys import logging import re logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") # 绝对路径的import sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../") from database.Procedure import Procedure from database.FindViewOriginalTable import FindViewOriginalTable class AutoViewReplace(object): """视图改原表,自动化: 1.自动查找视图,rptuser.v_, from v_, join v_ 2.data_area 处理:行首加--, behead where add 1=1 -- """ def __init__(self): pass def procedure_view_set(self, proc_name: str, schema="RPTUSER") -> set: """返回视图集合 方法2:正则匹配 """ procedure = Procedure(proc_name, schema) proc_cont = procedure.read_proc_cont() # find view name \w match word and line not comma view_pattern = r"V_\w*_ALL" view_list = re.findall(view_pattern, proc_cont, flags=re.IGNORECASE) return set(view_list) # def procedure_view_set_bak(self, proc_name: str) -> set: # """返回视图集合 # 方法1:找到视图的位置,根据空格循环截取 # """ # view_set = set() # procedure = Procedure(proc_name) # proc_cont = procedure.read_proc_cont() # # logging.info(f"proc_cont:{proc_cont}") # # find view name # while self.view_index(proc_cont) > -1: # view_ind = self.view_index(proc_cont) # proc_from_index = proc_cont[view_ind:] # view_name, *proc_cont_list = proc_from_index.split(" ") # view_name = view_name.replace("\n", "") # if not self.is_whitelist(view_name): # view_set.add(view_name) # # deal with proc_cont_list # proc_cont = " ".join(proc_cont_list) # return view_set # def view_index(self, proc_cont: str) -> int: # """检查是否存在要改的视图 """ # index = proc_cont.find("RPTUSER.V_") # return index def is_whitelist(self, view_name: str) -> bool: """是否白名单(不需要修改)的视图""" return False def view_replace(self, proc_name: str, schema="RPTUSER"): """替换视图""" proc_view_set = self.procedure_view_set(proc_name, schema) logging.debug(f"proc_view_set:{proc_view_set}") if not proc_view_set: return # get view table proc_view_dict = {} view_obj = FindViewOriginalTable() for view in proc_view_set: table_name = view_obj.get_view_original_table(view) proc_view_dict[view] = table_name procedure = Procedure(proc_name, schema) # add log procedure.write_header_log("view replace with table") # split two and procedure.modify_proc_by_line() procedure.replace_view_with_table(proc_view_dict) logging.info(f"{proc_name} 视图已经改为原表!") # procedure.data_area_deal() # logging.info(f"{proc_name} data_area处理完成!") def main(self, proc_name: str, schema="RPTUSER"): """replace_view_and_data_area""" self.view_replace(proc_name, schema) procedure = Procedure(proc_name, schema) procedure.data_area_deal() if __name__ == "__main__": # if len(sys.argv) <= 1: # logging.info("Please input procedure_name") # sys.exit(1) # proc_name = sys.argv[1] # obj = AutoViewReplace() # obj.main(proc_name) obj = AutoViewReplace() obj.main("p_rpt_lon300_1") # obj.main("p_rpt_dep906")
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,970
klgentle/lc_python
refs/heads/master
/scrapy_test/scrapy_test.py
import requests def requests_auth_login(): s = requests.Session() r = s.get("http://100.11.94.171:8080/BOE/CMC", auth=("administrator", "Yxjk123")) print(r.status_code) print(r.text) # print(r.url) # print(r.cookies) r2 = s.get("http://100.11.94.171:8080/BOE/CMC/1901061353/admin/logon.faces") print(r2.status_code) #print("r2-------------\n", r2.text) def requests_post_login(): login_data = { "_id2:logon:USERNAME": "administrator", "_id2:logon:PASSWORD": "Yxjk123", } r = requests.post("http://100.11.94.171:8080/BOE/CMC", data=login_data) print(r.status_code) print(r.text) print(r.url) print(r.cookies) def requests_create_promotion(): promotion_jobs_url = "http://100.11.94.171:8080/BOE/CMC/1901061353/admin/App/home.faces?service=%2Fadmin%2FApp%2FappService.jsp&appKind=CMC&bttoken=MDAwRD1EPEowR11AV0hpa05bPV9Va281ZDBlaWkBSNjAEQ" r = requests.get(promotion_jobs_url) print(r.status_code) print(r.text) print(r.url) print(r.cookies) if __name__ == "__main__": requests_auth_login()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,971
klgentle/lc_python
refs/heads/master
/leet_code/medium_case/stoneGame.py
from functools import lru_cache class Solution: def stoneGame(self, piles): N = len(piles) @lru_cache(None) def dp(i, j): # The value of the game [piles[i], piles[i+1], ..., piles[j]]. if i > j: return 0 parity = (j - i - N) % 2 if parity == 1: # first player return max(piles[i] + dp(i+1,j), piles[j] + dp(i,j-1)) else: return min(-piles[i] + dp(i+1,j), -piles[j] + dp(i,j-1)) return dp(0, N - 1) > 0
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,972
klgentle/lc_python
refs/heads/master
/stock_pandas/Advanced2.py
Date=input("Enter a date between 8/8/2018 and 8/7/2019: ") share1=int(input("Enter the number of shares of IBM:\n")) share2=int(input("Enter the number of shares of MSFT:\n")) #Date_str='3/29/2019' #share1=4666 #share2=3222 date_list = Date_str.split('/') Date = date_list[-1]+'/'+date_list[0]+'/' +date_list[1] #print(Date) #import datetime #date_time = datetime.datetime.strptime(Date_str,'%m/%d/%Y') #Date = date_time.strftime('%Y/%m/%d') import pandas as pd IBM=pd.read_csv('IBM.csv') price1=float(IBM[(IBM['Date']==Date)]['Adj Close']) #print(price1) total1=price1*share1 #print(total1) MSFT=pd.read_csv('MSFT.csv') price2=float(IBM[(MSFT['Date']==Date)]['Adj Close']) total2=price2*share2 total=total1+total2 print("Your portfolio report for:",Date) print("The adjusted close price of IBM was:","$",price1,"and you had",share1) print("The adjusted close price of MSFT was:","$",price2,"and you had",share2) print("Your total portfolio value was ${:.2f}".format(total))
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,973
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/tree/p0110_Balanced_Binary_Tree.py
""" 110. Balanced Binary Tree Easy Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree in which the left and right subtrees of every node differ in height by no more than 1. Example 1: Input: root = [3,9,20,null,null,15,7] Output: true Example 2: Input: root = [1,2,2,3,3,null,null,4,4] Output: false """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def getdepath(self, root:TreeNode): if not root: return 0 return 1 + max(self.getdepath(root.left), self.getdepath(root.right)) def isBalanced(self, root: TreeNode) -> bool: # get depath # compare if not root: return True lp = self.getdepath(root.left) rp = self.getdepath(root.right) #print(f"lp:{lp}, rp:{rp}") if abs(lp - rp) > 1: return False return self.isBalanced(root.left) and self.isBalanced(root.right)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,974
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/array/p0316_Remove_Duplicate_Letters.py
""" 316. Remove Duplicate Letters Medium Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results. Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/ Example 1: Input: s = "bcabc" Output: "abc" Example 2: Input: s = "cbacdcbc" Output: "acdb" """ from collections import Counter class Solution: def removeDuplicateLetters(self, s: str) -> str: """ 去重,最简单的是建立清单,如果不在清单中就加入,在就跳过; 如果要保证 lexicographical order,可以在加入时,弹出之前加入的元素(条件是弹出的元素,后面还可以加入)。 """ count = Counter(s) stack = [] for c in s: count[c] -= 1 if c not in stack: while stack and c < stack[-1] and count[stack[-1]] > 0: stack.pop() stack.append(c) return "".join(stack)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,975
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/dynamic_programming/p0494_Target_Sum.py
""" 494. Target Sum Medium You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol. Find out how many ways to assign symbols to make sum of integers equal to target S. Example 1: Input: nums is [1, 1, 1, 1, 1], S is 3. Output: 5 Explanation: -1+1+1+1+1 = 3 +1-1+1+1+1 = 3 +1+1-1+1+1 = 3 +1+1+1-1+1 = 3 +1+1+1+1-1 = 3 There are 5 ways to assign symbols to make the sum of nums be target 3. """ class Solution: def findTargetSumWays(self, nums: List[int], S: int) -> int: self.target = S self.nums = nums self.memo = {} return self.dp(len(nums)-1, 0) def dp(self, index, curr_sum): # Optimize if (index, curr_sum) in self.memo: return self.memo[(index, curr_sum)] # base case if index < 0 and curr_sum == self.target: return 1 if index < 0: return 0 # decision positive = self.dp(index-1, curr_sum + self.nums[index]) negetive = self.dp(index-1, curr_sum - self.nums[index]) self.memo[(index, curr_sum)] = positive + negetive return self.memo[(index, curr_sum)]
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,976
klgentle/lc_python
refs/heads/master
/stock_pandas/ConvertibleBondAnalysis.py
""" 1.分析可转债近一年收益情况,如果按海哥的策略(现价/转股价>= 96%),一年单账户可以获利多少 2.需要准备多少资金, 3.如果修改策略单账户最多获利多少, 4.一个人最多可以申请几个账户 5.理论上一个人动用多个账户一年最多可以赚多少? """ import pandas as pd import pandas_datareader.data as web import time class ConvertibleBondAnalysis(object): def __init__(self): self._bond_data = pd.read_csv("convertibile_bond.csv") #self.set_open_price() #self._bond_data_with_price = pd.read_csv("convertibile_bond_with_price.csv", "GB2312") @staticmethod def date_change_format(from_date: str) -> str: """ from_date: %Y/%m/%d out: %Y-%m-%d """ input_date = time.strptime(from_date, "%Y/%m/%d") return time.strftime("%Y-%m-%d", input_date) def get_bond_open_value(self, code: str, open_date: str) -> int: # open_date format "2017-01-01" print(f"enter get_bond_open_value for test ----------------- code:{code}, open_date:{open_date}") if open_date > "2019-11-04": return 0 try: bond_data = web.get_data_yahoo(code, open_date, open_date) except Exception as e: print("Error:", e.__doc__, e.__cause__, e.__context__) return 0 print(bond_data.loc[open_date, "Open"]) # 取第一天开板价格 return bond_data.loc[open_date, "Open"] def get_bond_open_value_print(self, code: str, open_date: str) -> int: # for test # open_date format "2017-01-01" #bond_data = web.get_data_yahoo(code, open_date, open_date) # print(bond_data.head()) # 取第一天开板价格 print(f"for test ----------------- code:{code}, open_date:{open_date}") #return bond_data.loc[open_date, "Open"] def set_open_price(self): #self._bond_data.loc[:, "open_price"] = [ # TODO check error KeyError: 'Date' open_price_list = [ self.get_bond_open_value( str(self._bond_data.iat[i,9]).rjust(6,"0") +".ss", #stock_code self.date_change_format(self._bond_data.iat[i,8]) #open_date ) for i in self._bond_data.index ] print(f"open_price_list: {open_price_list}") #self._bond_data.to_csv( # "./convertibile_bond_with_price.csv", sep=",", header=True #) def test_data_detect(self): #print(self._bond_data.iloc[2]) #print(type(self._bond_data.iloc[2])) #print("-------------", self._bond_data.iloc[2][0]) print("------------- head", self._bond_data.head()) print("------------- iat[1,8]", self._bond_data.iat[1,8]) print("------------- iat[1,9]", self._bond_data.iat[1,9]) print("------------- iat[1,10]", self._bond_data.iat[1,10]) def test_data_detect2(self): print(self._bond_data_with_price.head()) print(self._bond_data_with_price.index) def test_data_index(self): for i in self._bond_data.index: print(i) if __name__ == "__main__": obj = ConvertibleBondAnalysis() # 用正股价格去推算可转债上市价格 #obj.get_bond_open_value("601818.ss", "2017-04-05") obj.get_bond_open_value("002174.ss", "2019-10-21") # print(obj.date_change_format("2017/4/5")) #obj.test_data_index() #obj.test_data_detect2() #obj.test_data_detect() #obj.set_open_price()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,977
klgentle/lc_python
refs/heads/master
/tests/test_subprogress.py
import subprocess import os os.chdir("/mnt/d/code_test/game_test/nsf") subprocess.Popen( [ "curl", "https://qpix.com/images/2020/03/27/svpd.jpg", "-o", "0_svpd.jpg", "--silent", ] )
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,978
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/linked_list/p0206_Reverse_Linked_List.py
""" 206. Reverse Linked List Easy Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both? """ # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseList(self, head: ListNode) -> ListNode: pre = None while head: # 取头结点 curr = head # 移动 head = head.next curr.next = pre pre = curr return pre
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,979
klgentle/lc_python
refs/heads/master
/cs61a/codetest_test.py
def print_factors(n): """Print the prime factors of N. >>> print_factors(180) 2 2 3 5 """ pass if __name__ == "__main__": import doctest doctest.testmod()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,980
klgentle/lc_python
refs/heads/master
/base_practice/tea.py
resugar=1.5 rebutter=1 reflour=2.75 recookies=48 num_cookies=int(input("Enter number of cookies:")) sugar_needed=(resugar/48)*num_cookies butter_needed=(rebutter/48)*num_cookies flour_needed=(reflour/48)*num_cookies print("You need",format(sugar_needed,'.2f'),"cups of sugar,",format(butter_needed,'.2f'),"cups of butter,",format(flour_needed,'.2f'),"cups of flour.")
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,981
klgentle/lc_python
refs/heads/master
/leet_code/medium_case/wordBreak.py
class Solution: """ # 139 Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. """ def wordBreak(self, s, wordDict:list)->bool: if not s: return True breakp = [0] for i in range(len(s) + 1): for j in breakp: if s[j:i] in wordDict: breakp.append(i) break print(f"breakp: {breakp}") return breakp[-1] == len(s)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,982
klgentle/lc_python
refs/heads/master
/automatic_office/decryptZipFile_v2.py
import os # import py7zr from itertools import product import subprocess filepath = r"D:\code_test\game_test\confidential_data" namepath = r"D:\code_test\game_test\confidential_data\pvideo.7z" def verify_password(pwd): cmd = f'7z t -p{pwd} {namepath}' #print(f"test cmd: {cmd}") status = subprocess.call(cmd) return status def unzip_file_other_folder(pwd): print(f'___________________________________ 正确的密码是:{pwd}') with open(r"D:\code_test\game_test\confidential_data\pvideo_pwd.txt", "w") as f: f.write(pwd) cmd = f'7z x -p{pwd} {namepath} -y -aos -o "{filepath}\girl"' subprocess.call(cmd) def decryptZipFile(length): chars = "pvideoklgirl0123456789" passwords = product(chars, repeat=length) for pwd in passwords: pwd = "".join(pwd) print(f'Try password {pwd} ...') status = verify_password(pwd) if status == 0: unzip_file_other_folder(pwd) return "Success" return "Failed" def bruteforce(): for length in range(1, 13): status = decryptZipFile(length) if status == "Success": return "Success" print("破解失败") return "Failed" if __name__ == '__main__': os.chdir(r"D:\code_test\game_test\confidential_data") # decryptZipFile("girl_r15.7z") # decryptZipFile() bruteforce() ### important call from cmd
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,983
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/tree/p0104_Maximum_Depth_of_Binary_Tree.py
""" 104. Maximum Depth of Binary Tree Easy Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Example 1: Input: root = [3,9,20,null,null,15,7] Output: 3 Example 2: Input: root = [1,null,2] Output: 2 Example 3: Input: root = [] Output: 0 Example 4: Input: root = [0] Output: 1 """ class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 depth = 0 q = collections.deque() q.append(root) while q: level = [] for _ in range(len(q)): x = q.popleft() level.append(x.val) if x.left: q.append(x.left) if x.right: q.append(x.right) depth += 1 return depth
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,984
klgentle/lc_python
refs/heads/master
/automatic_office/DealInterval.py
import datetime #import pysnooper #import pprint import os import sys # 绝对路径的import sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../") """ 根据工作日期,生成周报模板 """ class DealInterval(object): def __init__(self): pass @staticmethod def get_from_end_str(date_tuple: tuple) -> str: """ date_tuple: (datetime.date(2020, 3, 5), datetime.date(2020, 3, 7)) """ return "-".join( [ datetime.datetime.strftime(date_tuple[0], "%Y%m%d"), datetime.datetime.strftime(date_tuple[1], "%Y%m%d"), ] ) @staticmethod def get_from_date(date_tuple: tuple) -> str: return datetime.datetime.strftime(date_tuple[0], "%Y-%m-%d") @staticmethod def get_end_date(date_tuple: tuple) -> str: return datetime.datetime.strftime(date_tuple[1], "%Y-%m-%d") # @pysnooper.snoop() def get_all_weekday_interval(self, weekdays: list, intervals=[]) -> list: # 查看一下,为什么默认值没有显示设置为空,结果会变? """ 返回每个时间区间构成的列表,如 [(date'2020-03-07',date'2020-03-07')] weekdays:[datetime.date(2020, 3, 5), datetime.date(2020, 3, 6), datetime.date(2020, 3, 7),datetime.date(2020, 3, 10), datetime.date(2020, 3, 13),datetime.date(2020, 3, 14)] """ if len(weekdays) == 1: intervals.append((weekdays[0], weekdays[0])) return intervals elif len(weekdays) <= 0: return intervals for i, date in enumerate(weekdays): # print(f"i:{i}, date:{date}") # pprint.pprint("intervals:%s" % intervals) # 如果是最后一个 if i == len(weekdays) - 1: intervals.append((weekdays[0], weekdays[-1])) return intervals if weekdays[i + 1] == date + datetime.timedelta(1): continue else: intervals.append((weekdays[0], date)) return self.get_all_weekday_interval(weekdays[i + 1 :], intervals) if __name__ == "__main__": obj = DealInterval()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,985
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/sliding_window/1004._Max_Consecutive_Ones_III.py
""" 1004. Max Consecutive Ones III Medium Given an array A of 0s and 1s, we may change up to K values from 0 to 1. Return the length of the longest (contiguous) subarray that contains only 1s. Example 1: Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2 Output: 6 Explanation: [1,1,1,0,0,1,1,1,1,1,1] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. Example 2: Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3 Output: 10 Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. """ class Solution: def longestOnes(self, A: List[int], K: int) -> int: left, right = 0, 0 windFreq = defaultdict(int) maxFreq = 0 maxLen = 0 while right < len(A): a = A[right] right += 1 windFreq[a] += 1 # 与第424题唯一的不同在于此处的 if, 只有取1时,才计算 maxFreq if a == 1: maxFreq = max(maxFreq, windFreq[a]) if (right - left) - maxFreq > K: windFreq[A[left]] -= 1 left += 1 else: maxLen = max(maxLen, right - left) return maxLen
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,986
klgentle/lc_python
refs/heads/master
/stock_pandas/stock_anal.py
""" fix records: 1. end date is 2019/8/16 2. add while, date input format 3. pd.contact -> pd.concat([df1, df2]) """ import pandas as pd from_date = "2018/1/17" to_date = "2019/8/16" # for test start = "2018-03-20" start = input("Enter the beginning date between 2018-1-17 and 2019-8-16: ") start_list = start.split("-") # date format start_date = ( start_list[0] + "/" + str(int(start_list[1])) + "/" + str(int(start_list[2])) ) # print(start_date) while start_date < from_date or start_date > to_date: print("Start date is out of the date range") start = input("Enter the beginning date between 2018-1-17 and 2019-8-16: ") start_list = start.split("-") # date format start_date = ( start_list[0] + "/" + str(int(start_list[1])) + "/" + str(int(start_list[2])) ) # for test end = '2018-08-16' end = input("Enter the ending date between 2018-1-17 and 2019-8-16: ") end_list = end.split("-") # date format end_date = end_list[0] + "/" + str(int(end_list[1])) + "/" + str(int(end_list[2])) # print(start_date) while end_date < start_date or end_date > to_date: if end_date < start_date: print("End date cannot be before start date") else: print("End date is out of the date range") end = input("Enter the ending date between 2018-1-17 and 2019-8-16: ") end_list = end.split("-") # date format end_date = end_list[0] + "/" + str(int(end_list[1])) + "/" + str(int(end_list[2])) print("Summary of stock prices from", start, "to", end) CMG = pd.read_csv("CMG.csv") COKE = pd.read_csv("COKE.csv") NKE = pd.read_csv("NKE.csv") # add Symbol for stock to mark length = len(CMG["Date"]) CMG["Symbol"] = ["CMG"] * length COKE["Symbol"] = ["COKE"] * length NKE["Symbol"] = ["NKE"] * length all_data = pd.concat([CMG, COKE, NKE]) all_data["Date"] = pd.to_datetime(all_data["Date"]) # 将数据类型转换为日期类型 all_data = all_data.set_index("Date") # 将date设置为index select = all_data.loc[start:end, ["Adj Close", "Symbol"]] # rename column for agg select = select.rename({"Adj Close": "Adj_Close"}, axis="columns") # get the begin data begining_price = select.loc[start:start, ["Adj_Close", "Symbol"]] # get the end data ending_price = select.loc[end:end, ["Adj_Close", "Symbol"]] # transfer into group by for join begin_group = begining_price.groupby("Symbol").max() end_group = ending_price.groupby("Symbol").max() # rename column for display begin_group = begin_group.rename({"Adj_Close": "Begining Price"}, axis="columns") end_group = end_group.rename({"Adj_Close": "Ending Price"}, axis="columns") # data format for display pd.options.display.float_format = "{:,.2f}".format stock_out = pd.DataFrame(select.groupby("Symbol").Adj_Close.agg(["min", "max", "mean"])) # rename column for display stock_out = stock_out.rename( {"min": "Minimum", "max": "Maximum", "mean": "Average"}, axis="columns" ) stock_out = pd.concat([begin_group, end_group, stock_out], axis="columns") print(stock_out)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,987
klgentle/lc_python
refs/heads/master
/automatic_office/CheckInForm.py
import datetime import logging import os import re import sys import time import platform logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s") # 绝对路径的import sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../") from automatic_office.Holiday import Holiday from docx import Document from docx.enum.table import WD_ALIGN_VERTICAL, WD_TABLE_ALIGNMENT from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.oxml.ns import qn from docx.shared import Cm, Inches, Pt class CheckInForm(object): """ word style """ def __init__(self, year_month: str): # date calculate # 本月5号到下月4号 if len(year_month) != 6: print("Please input year_month with format: YYYYMM!") sys.exit(1) self.__input_year = int(year_month[:4]) self.__input_month = int(year_month[4:]) self.__date_start = self.calculate_date_start() self.__date_end = self.calculate_date_end() self.__work_date_start = self.__date_start.strftime("%Y-%m-%d") self.__work_date_end = self.__date_end.strftime("%Y-%m-%d") self.__year_month = year_month def calculate_date_start(self) -> datetime.date: return datetime.date(self.__input_year, self.__input_month, 5) def calculate_date_end(self) -> datetime.date: year = self.__input_year month = self.__input_month + 1 if month == 13: month = 1 year += 1 return datetime.date(year, month, 4) def get_all_nature_date(self) -> list: """ 返回所有日期列表 """ all_nature_date = [] from_date = self.__date_start while from_date.__le__(self.__date_end): all_nature_date.append(from_date) from_date += datetime.timedelta(1) return all_nature_date def get_all_work_date(self) -> list: """ 返回所有工作日列表 """ all_work_date = [] from_date = self.__date_start holiday_obj = Holiday() while from_date.__le__(self.__date_end): # time.sleep(1) # skip holiday if not holiday_obj.is_holiday(from_date.strftime("%Y%m%d")): all_work_date.append(from_date) from_date += datetime.timedelta(1) #logging.debug( # "debug work date --{0}".format(from_date.strftime("%Y%m%d")) #) # TODO write work_date return all_work_date def check_in_add_table(self, document: object, form_type: str): head_list = ["序号", "日期", "签到时间", "签退时间", "备注"] table = document.add_table(rows=1, cols=len(head_list), style="Table Grid") hdr_cells = table.rows[0].cells for i in range(len(head_list)): hdr_cells[i].text = head_list[i] hdr_cells[i].paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER # 水平居中 hdr_cells[i].vertical_alignment = WD_ALIGN_VERTICAL.CENTER # 垂直居中 hdr_cells[i].width = Cm(2.82) date_list = [] if form_type.lower() == "normal": date_list = self.get_all_work_date() elif form_type.lower() == "overtime": date_list = self.get_all_nature_date() for ind, date in enumerate(date_list): row_cells = table.add_row().cells row_cells[0].text = str(ind + 1) row_cells[1].text = date.strftime("%Y-%m-%d") # TODO set font name # font.name = u'Calibri' # run._element.rPr.rFonts.set(qn('w:eastAsia'), u'Calibri') row_cells[2].text = "" row_cells[3].text = "" row_cells[4].text = "" # 设置水平居中 for i in range(len(head_list)): row_cells[i].paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER # 水平居中 row_cells[i].vertical_alignment = WD_ALIGN_VERTICAL.CENTER # 垂直居中 row_cells[i].width = Cm(2.82) # 设置行高 for row in table.rows: if form_type.lower() == "normal": row.height = Cm(0.88) elif form_type.lower() == "overtime": row.height = Cm(0.70) return table def write_form(self, form_type: str): form_type_name_dict = {"overtime": "带加班", "normal": "正常"} form_type_head_dict = {"overtime": "签到表(含加班/调休/请假)", "normal": "签到表"} document = Document() document.styles["Normal"].font.name = u"宋体" # 微软雅黑 document.styles["Normal"].font.size = Pt(10.5) document.styles["Normal"]._element.rPr.rFonts.set(qn("w:eastAsia"), u"宋体") # 页面布局 sec = document.sections[0] # sections对应文档中的“节” sec.top_margin = Cm(2.3) sec.bottom_margin = Cm(2.3) sec.page_height = Cm(29.7) sec.page_with = Cm(21) # add header paragraph = document.add_paragraph() run = paragraph.add_run(form_type_head_dict.get(form_type)) font = run.font # set font name # font.name = u'宋体' # run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') font.size = Pt(16) # 三号 paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER paragraph_format = paragraph.paragraph_format # paragraph_format.line_spacing = 1.5 # 1.5倍行间距 # paragraph_format.space_after =Pt(0) #设置段后间距 paragraph = document.add_paragraph( "姓名: 日期:{} 至 {}".format(self.__work_date_start, self.__work_date_end) ) paragraph.alignment = WD_ALIGN_PARAGRAPH.LEFT paragraph_format = paragraph.paragraph_format paragraph_format.first_line_indent = Inches(0.3) # 首行缩进 paragraph_format.left_indent = Cm(3.7) # 左侧缩进3.7cm # paragraph_format.line_spacing = 1.5 # 1.5倍行间距 paragraph_format.space_after = Pt(0) # 设置段后间距 table = self.check_in_add_table(document, form_type) table.alignment = WD_TABLE_ALIGNMENT.CENTER document.save( os.path.join( "doc_file", "文思员工-{0}月签到表_新模版_{1}.docx".format( self.__input_month, form_type_name_dict.get(form_type) ), ) ) logging.info("Done!") if __name__ == "__main__": if len(sys.argv) <= 1: logging.info("Please input year_moth(YYYYMM)") sys.exit(1) obj = CheckInForm(sys.argv[1]) obj.write_form("overtime") obj.write_form("normal")
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,988
klgentle/lc_python
refs/heads/master
/base_practice/assets.py
def main(): """ num -> nums, 变量区分开来,不要混用了 ave should not in cycle """ nums=int(input("Enter the number of assets:")) portfolio=0.00 try: record_file=open('record.txt','w') for num in range(1,nums+1): print("****** For asset",num,"******") name=str(input("Enter the name of the asset:")) while not name[0].isalpha(): print("Asset name must start with a letter!") name=str(input("Enter the name of the asset:")) value=input("Enter the value of the asset:") while not value.isdigit(): print("Asset value must be a number!") value=input("Enter the value of the asset:") value = int(value) portfolio+=value record_file.write(str(name)+"\n") record_file.close() ave=portfolio/nums print("The portfolio has the following",nums,"assets:") record_file=open('record.txt','r') name = record_file.readline() while name !='': print(name,"\n\n\n",sep='') name = record_file.readline() record_file.close() print("The portfolio is worth $",format(portfolio,',.2f')) print("The average of the asset is $",format(ave,'.2f')) except ValueError: print("Asset name must start with a letter!") print("Asset value must be a number!") main()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,989
klgentle/lc_python
refs/heads/master
/plt/bar_test.py
from matplotlib import pyplot as plt num_list = [6,4,2,0,3,2,0,3,1,4,5,3,2,7,5,3,0,1,2,1,3,4,6,8,1,3] length = range(len(num_list)) plt.bar(length,num_list) plt.show()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,990
klgentle/lc_python
refs/heads/master
/code_in_books/lp3thw/ex13_argv.py
from sys import argv script, first, second, third = argv print("Script is: ", script) print(f"Your first variable is: {first}" ) print(f"Your second variable is: {second}" ) print(f"Your third variable is: {third}" )
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,991
klgentle/lc_python
refs/heads/master
/scrapy_test/ScrapyBoForUpdate.py
""" TODO 写一个爬虫,从服务器取最新Bo,然后保存到本地 """ class ScrapyBoForUpdate(object): def __init__(self): self.bo_url = r"http://100.11.94.171:8080/BOE/BI" def login(self): pass
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,992
klgentle/lc_python
refs/heads/master
/data_structure/SStack.py
class StackUnderflow(ValueError): pass class SStack(): def __init__(self): self._elems = [] def is_empty(self): return self._elems == [] def top(self): if self._elems == []: raise StackUnderflow("In SStack.top()") return self._elems[-1] def push(self, elem): self._elems.append(elem) def pop(self): if self._elems == []: raise StackUnderflow("In SStack.op()") return self._elems.pop() if __name__ == "__main__": a = SStack() a.push(1) a.push(2) a.push(3) print(a.pop()) print(a.top()) a.top()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,993
klgentle/lc_python
refs/heads/master
/vs_code/envelopes.py
def compare(a,b): if a[0] == b[0]: return b[1] - a[1] return a[0] - b[0] # 列表 envelopes = [[5,4],[6,4],[6,7],[2,3]] # 指定第二个元素排序 envelopes.sort(key=compare) print(envelopes)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,994
klgentle/lc_python
refs/heads/master
/leet_code/medium_case/0394_decode_string.py
class Solution: def decodeString(self, s: str) -> str: stack = [] curString = "" curNum = 0 for c in s: if c.isdigit(): curNum = curNum * 10 + int(c) elif c == "[": stack.append(curString) stack.append(curNum) curString = "" curNum = 0 elif c == "]": num = stack.pop() preString = stack.pop() curString = preString + curString * num else: curString += c print("out:", curString) return curString a = Solution() s = "3[a2[c]]" print("input:", s) a.decodeString(s)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,995
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/tree/p0230_Kth_Smallest_Element_in_a_BST.py
""" Given the root of a binary search tree, and an integer k, return the kth (1-indexed) smallest element in the tree. Example 1: Input: root = [3,1,4,null,2], k = 1 Output: 1 """ class Solution: def __init__(self): self.treeList = [] def kthSmallest(self, root: TreeNode, k: int) -> int: self.constructList(root, k) return self.treeList[k - 1] def constructList(self, root, k): if not root: return # print(self.treeList) # 跳过不需要的部分 if len(self.treeList) >= k: return self.treeList self.constructList(root.left, k) self.treeList.append(root.val) self.constructList(root.right, k)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,996
klgentle/lc_python
refs/heads/master
/stock_pandas/plt_bar3.py
import matplotlib.pyplot as plt import pandas as pd # x 是x轴,y是height, loan = pd.read_csv("loan.csv") # 单列时sort不用写by x = loan["Credit_score"].drop_duplicates().sort_values() #print(x) y = loan["Credit_score"].groupby(loan["Credit_score"]).count() #print(y) #x = [625, 650, 675, 700, 725, 750, 775, 800] #y = [2.0, 2.0, 1.0, 3.0, 4.0, 2.0, 1.0, 2.0] p1 = plt.bar(x, height=y, width=2) plt.title("Credit_score") plt.grid(axis='y') plt.grid(axis='x') plt.show()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,997
klgentle/lc_python
refs/heads/master
/leet_code/easy_case/minCostClimbingStairs.py
class Solution: # leetcode 746. 使用最小花费爬楼梯 def minCostClimbingStairs(self, cost: List[int]) -> int: cost.append(0) # add zero to jump to top c = [] c.append(cost[0]) # c[0], c[1] c.append(cost[1]) l = len(cost) for i in range(2,l): c.append(min(c[i-2] + cost[i], c[i-1]+ cost[i])) print(f"c: {c}") print(f"min cost: {c[-1]}") return c[-1]
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,998
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/dynamic_programming/p0416_Partition_Equal_Subset_Sum.py
""" Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. Example 1: Input: nums = [1,5,11,5] Output: true Explanation: The array can be partitioned as [1, 5, 5] and [11]. Example 2: Input: nums = [1,2,3,5] Output: false Explanation: The array cannot be partitioned into equal sum subsets. """ class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: # 子背包问题 nums_sum = sum(nums) if nums_sum % k != 0: return False sub_sum = int(nums_sum / 2) dp = [False] * (sub_sum + 1) dp[0] = True for i in range(len(nums)): # 不需要对dp[0]赋值 for j in range(sub_sum,0,-1): if j >= nums[i-1]: dp[j] = dp[j] or dp[j - nums[i-1]] #print(f"{dp}") return dp[sub_sum]
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
57,999
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/tree/p0113_Path_Sum_II.py
""" 113. Path Sum II Medium Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where each path's sum equals targetSum. A leaf is a node with no children. Example 1: Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 Output: [[5,4,11,2],[5,8,4,5]] Example 2: Input: root = [1,2,3], targetSum = 5 Output: [] Example 3: Input: root = [1,2], targetSum = 0 Output: [] """ class Solution: def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]: res = [] self.dfs(root, targetSum, [], res) return res def dfs(self, root: TreeNode, targetSum: int, ls, res): if root: if not root.left and not root.right and root.val == targetSum: ls.append(root.val) res.append(ls) # 将列表直接在参数中运算,左右就可以独立不受影响 self.dfs(root.left, targetSum-root.val, ls+[root.val], res) self.dfs(root.right, targetSum-root.val, ls+[root.val], res)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,000
klgentle/lc_python
refs/heads/master
/leet_code/easy_case/isHappy.py
class Solution: def isHappy(self, n: int) -> bool: m = 0 return False if self.squareSum(n,m) != 1 else True def squareSum(self, n: int, m:int) -> int: m += 1 s = str(n) sum = 0 if m > 9: return -1 if len(s) > 1: for i in s: sum += int(i) ** 2 else: sum += n ** 2 #print(f"sum:{sum}") return 1 if sum == 1 else self.squareSum(sum,m) if __name__ == '__main__': a = Solution() a.isHappy(2)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,001
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/sliding_window/p0567_Permutation_in_String.py
""" 567. Permutation in String Medium Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string. Example 1: Input: s1 = "ab" s2 = "eidbaooo" Output: True Explanation: s2 contains one permutation of s1 ("ba"). Example 2: Input:s1= "ab" s2 = "eidboaoo" Output: False """ class Solution: def checkInclusion(self, t: str, s: str) -> bool: """ 套用滑动窗口的框架,提前收缩窗口,这样可以保证进来的是目标字符的排列 """ if t in s or t[::-1] in s: return True need = {} wind = {} for c in t: if c in need: need[c] += 1 else: need[c] = 1 left, right = 0, 0 valid = 0 while right < len(s): c = s[right] right += 1 if c in need: if c in wind: wind[c] += 1 else: wind[c] = 1 if wind[c] == need[c]: valid += 1 # 提前收缩窗口,保证窗口中全为想要的字符串 while right - left >= len(t): if valid == len(need.keys()): return True d = s[left] left += 1 if d in need: if wind[d] == need[d]: valid -= 1 wind[d] -= 1 return False
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,002
klgentle/lc_python
refs/heads/master
/leet_code/easy_case/missingNumber.py
class Solution: def missingNumber(self, nums: list) -> int: l = len(nums) lst = [i for i in range(0,l+1)] for i in set(lst) - set(nums): return i if __name__ == '__main__': a = Solution() #a.missingNumber([3,0,1]) a.missingNumber([0])
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,003
klgentle/lc_python
refs/heads/master
/leet_code/top_interview_questions/Medium_Case/P0227_Basic_Calculator_II_complex.py
class Solution: def calculate(self, s: str) -> int: if s == '0': return 0 s2 = s.replace(" ",'') if s2.isnumeric(): return int(s2) out = 0 length = len(s2) num_list = [] method_list = [] a = s2[0] # put all number and method in list for i in range(1,length): if s2[i].isnumeric(): a += s2[i] else: a = int(a) num_list.append(a) a= '' method = s2[i] method_list.append(method) # the last number to add a = int(a) num_list.append(a) print(f"num_list:{num_list}") print(f"method_list:{method_list}") mul = 1 sum = 0 method = method_list[0] # to deal with the first number if method in ('+','-'): out += num_list[0] sum += num_list[0] elif method in ('*','/'): mul = num_list[0] out = sum + mul print(f"mul:{mul}") print(f"out:{out}") for j in range(len(method_list)): method = method_list[j] next_method = None if j != len(method_list) -1: next_method = method_list[j+1] num = num_list[j+1] if method == '+': if next_method in ('*','/'): mul = num sum = out else: sum += num out += num elif method == '-': if next_method in ('*','/'): mul = -num sum = out else: sum -= num out -= num elif method == '*': mul *= num out = sum + mul elif method == '/': mul = int(mul / num) out = sum + mul """ print(f"mul:{mul}") print(f"sum:{sum}") print(f"out:{out}") print(f"mul:{mul}") """ print(f"out:{out}") return out
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,004
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/tree/p0101_Symmetric_Tree_2.py
""" 101. Symmetric Tree Easy Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 1 / \ 2 2 / \ / \ 3 4 4 3 But the following [1,2,2,null,3,null,3] is not: 1 / \ 2 2 \ \ 3 3 Follow up: Solve it both recursively and iteratively. """ class Solution: def isSymmetric(self, root: TreeNode) -> bool: if not root: return True # 每一层结点,应该是对称的 q = collections.deque() q.append(root) while q: level = [] for _ in range(len(q)): x = q.popleft() if not x: level.append(-1) else: level.append(x.val) q.append(x.left) q.append(x.right) #print(f"level:{level}") if level != level[::-1]: return False return True
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}