diff --git a/codes/python/.gitignore b/codes/python/.gitignore index bee8a64b7..ff6f73153 100644 --- a/codes/python/.gitignore +++ b/codes/python/.gitignore @@ -1 +1,3 @@ __pycache__ + +test_all.sh diff --git a/codes/python/chapter_array_and_linkedlist/array.py b/codes/python/chapter_array_and_linkedlist/array.py index ddc0fd10f..13604ab8e 100644 --- a/codes/python/chapter_array_and_linkedlist/array.py +++ b/codes/python/chapter_array_and_linkedlist/array.py @@ -4,11 +4,9 @@ Created Time: 2022-11-25 Author: Krahets (krahets@163.com) """ -import sys, os.path as osp -sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) -from modules import * +import random -def random_access(nums: List[int]) -> int: +def random_access(nums: list[int]) -> int: """ 随机访问元素 """ # 在区间 [0, len(nums)-1] 中随机抽取一个数字 random_index = random.randint(0, len(nums) - 1) @@ -18,7 +16,7 @@ def random_access(nums: List[int]) -> int: # 请注意,Python 的 list 是动态数组,可以直接扩展 # 为了方便学习,本函数将 list 看作是长度不可变的数组 -def extend(nums: List[int], enlarge: int) -> List[int]: +def extend(nums: list[int], enlarge: int) -> list[int]: """ 扩展数组长度 """ # 初始化一个扩展长度后的数组 res = [0] * (len(nums) + enlarge) @@ -28,7 +26,7 @@ def extend(nums: List[int], enlarge: int) -> List[int]: # 返回扩展后的新数组 return res -def insert(nums: List[int], num: int, index: int) -> None: +def insert(nums: list[int], num: int, index: int) -> None: """ 在数组的索引 index 处插入元素 num """ # 把索引 index 以及之后的所有元素向后移动一位 for i in range(len(nums) - 1, index, -1): @@ -36,13 +34,13 @@ def insert(nums: List[int], num: int, index: int) -> None: # 将 num 赋给 index 处元素 nums[index] = num -def remove(nums: List[int], index: int) -> None: +def remove(nums: list[int], index: int) -> None: """ 删除索引 index 处元素 """ # 把索引 index 之后的所有元素向前移动一位 for i in range(index, len(nums) - 1): nums[i] = nums[i + 1] -def traverse(nums: List[int]) -> None: +def traverse(nums: list[int]) -> None: """ 遍历数组 """ count = 0 # 通过索引遍历数组 @@ -52,7 +50,7 @@ def traverse(nums: List[int]) -> None: for num in nums: count += 1 -def find(nums: List[int], target: int) -> int: +def find(nums: list[int], target: int) -> int: """ 在数组中查找指定元素 """ for i in range(len(nums)): if nums[i] == target: @@ -62,9 +60,9 @@ def find(nums: List[int], target: int) -> int: """ Driver Code """ if __name__ == "__main__": """ 初始化数组 """ - arr: List[int] = [0] * 5 + arr: list[int] = [0] * 5 print("数组 arr =", arr) - nums: List[int] = [1, 3, 2, 5, 4] + nums: list[int] = [1, 3, 2, 5, 4] print("数组 nums =", nums) """ 随机访问 """ @@ -72,7 +70,7 @@ if __name__ == "__main__": print("在 nums 中获取随机元素", random_num) """ 长度扩展 """ - nums: List[int] = extend(nums, 3) + nums: list[int] = extend(nums, 3) print("将数组长度扩展至 8 ,得到 nums =", nums) """ 插入元素 """ diff --git a/codes/python/chapter_array_and_linkedlist/linked_list.py b/codes/python/chapter_array_and_linkedlist/linked_list.py index 8fb6e10b2..781e0ba4b 100644 --- a/codes/python/chapter_array_and_linkedlist/linked_list.py +++ b/codes/python/chapter_array_and_linkedlist/linked_list.py @@ -23,7 +23,7 @@ def remove(n0: ListNode) -> None: n1 = P.next n0.next = n1 -def access(head: ListNode, index: int) -> Optional[ListNode]: +def access(head: ListNode, index: int) -> ListNode | None: """ 访问链表中索引为 index 的结点 """ for _ in range(index): if not head: diff --git a/codes/python/chapter_array_and_linkedlist/list.py b/codes/python/chapter_array_and_linkedlist/list.py index 9c0a5f31c..9a3cdbbae 100644 --- a/codes/python/chapter_array_and_linkedlist/list.py +++ b/codes/python/chapter_array_and_linkedlist/list.py @@ -4,60 +4,55 @@ Created Time: 2022-11-25 Author: Krahets (krahets@163.com) """ -import sys, os.path as osp -sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) -from modules import * - - """ Driver Code """ if __name__ == "__main__": """ 初始化列表 """ - list: List[int] = [1, 3, 2, 5, 4] - print("列表 list =", list) + arr: list[int] = [1, 3, 2, 5, 4] + print("列表 arr =", arr) """ 访问元素 """ - num: int = list[1] + num: int = arr[1] print("访问索引 1 处的元素,得到 num =", num) """ 更新元素 """ - list[1] = 0 - print("将索引 1 处的元素更新为 0 ,得到 list =", list) + arr[1] = 0 + print("将索引 1 处的元素更新为 0 ,得到 arr =", arr) """ 清空列表 """ - list.clear() - print("清空列表后 list =", list) + arr.clear() + print("清空列表后 arr =", arr) """ 尾部添加元素 """ - list.append(1) - list.append(3) - list.append(2) - list.append(5) - list.append(4) - print("添加元素后 list =", list) + arr.append(1) + arr.append(3) + arr.append(2) + arr.append(5) + arr.append(4) + print("添加元素后 arr =", arr) """ 中间插入元素 """ - list.insert(3, 6) - print("在索引 3 处插入数字 6 ,得到 list =", list) + arr.insert(3, 6) + print("在索引 3 处插入数字 6 ,得到 arr =", arr) """ 删除元素 """ - list.pop(3) - print("删除索引 3 处的元素,得到 list =", list) + arr.pop(3) + print("删除索引 3 处的元素,得到 arr =", arr) """ 通过索引遍历列表 """ count: int = 0 - for i in range(len(list)): + for i in range(len(arr)): count += 1 """ 直接遍历列表元素 """ count: int = 0 - for n in list: + for n in arr: count += 1 """ 拼接两个列表 """ - list1: List[int] = [6, 8, 7, 10, 9] - list += list1 - print("将列表 list1 拼接到 list 之后,得到 list =", list) + arr1: list[int] = [6, 8, 7, 10, 9] + arr += arr1 + print("将列表 arr1 拼接到 arr 之后,得到 arr =", arr) """ 排序列表 """ - list.sort() - print("排序列表后 list =", list) + arr.sort() + print("排序列表后 arr =", arr) diff --git a/codes/python/chapter_array_and_linkedlist/my_list.py b/codes/python/chapter_array_and_linkedlist/my_list.py index 8ef1fc945..fd1062630 100644 --- a/codes/python/chapter_array_and_linkedlist/my_list.py +++ b/codes/python/chapter_array_and_linkedlist/my_list.py @@ -4,16 +4,12 @@ Created Time: 2022-11-25 Author: Krahets (krahets@163.com) """ -import sys, os.path as osp -sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) -from modules import * - class MyList: """ 列表类简易实现 """ def __init__(self): """ 构造方法 """ self.__capacity: int = 10 # 列表容量 - self.__nums: List[int] = [0] * self.__capacity # 数组(存储列表元素) + self.__nums: my_list[int] = [0] * self.__capacity # 数组(存储列表元素) self.__size: int = 0 # 列表长度(即当前元素数量) self.__extend_ratio: int = 2 # 每次列表扩容的倍数 @@ -76,7 +72,7 @@ class MyList: # 更新列表容量 self.__capacity = len(self.__nums) - def to_array(self) -> List[int]: + def to_array(self) -> list[int]: """ 返回有效长度的列表 """ return self.__nums[:self.__size] @@ -84,35 +80,35 @@ class MyList: """ Driver Code """ if __name__ == "__main__": """ 初始化列表 """ - list = MyList() + my_list = MyList() """ 尾部添加元素 """ - list.add(1) - list.add(3) - list.add(2) - list.add(5) - list.add(4) - print("列表 list = {} ,容量 = {} ,长度 = {}" - .format(list.to_array(), list.capacity(), list.size())) + my_list.add(1) + my_list.add(3) + my_list.add(2) + my_list.add(5) + my_list.add(4) + print("列表 my_list = {} ,容量 = {} ,长度 = {}" + .format(my_list.to_array(), my_list.capacity(), my_list.size())) """ 中间插入元素 """ - list.insert(6, index=3) - print("在索引 3 处插入数字 6 ,得到 list =", list.to_array()) + my_list.insert(6, index=3) + print("在索引 3 处插入数字 6 ,得到 my_list =", my_list.to_array()) """ 删除元素 """ - list.remove(3) - print("删除索引 3 处的元素,得到 list =", list.to_array()) + my_list.remove(3) + print("删除索引 3 处的元素,得到 my_list =", my_list.to_array()) """ 访问元素 """ - num = list.get(1) + num = my_list.get(1) print("访问索引 1 处的元素,得到 num =", num) """ 更新元素 """ - list.set(0, 1) - print("将索引 1 处的元素更新为 0 ,得到 list =", list.to_array()) + my_list.set(0, 1) + print("将索引 1 处的元素更新为 0 ,得到 my_list =", my_list.to_array()) """ 测试扩容机制 """ for i in range(10): # 在 i = 5 时,列表长度将超出列表容量,此时触发扩容机制 - list.add(i) - print("扩容后的列表 list = {} ,容量 = {} ,长度 = {}" - .format(list.to_array(), list.capacity(), list.size())) + my_list.add(i) + print("扩容后的列表 my_list = {} ,容量 = {} ,长度 = {}" + .format(my_list.to_array(), my_list.capacity(), my_list.size())) diff --git a/codes/python/chapter_computational_complexity/leetcode_two_sum.py b/codes/python/chapter_computational_complexity/leetcode_two_sum.py index edffd281e..fd7653d4d 100644 --- a/codes/python/chapter_computational_complexity/leetcode_two_sum.py +++ b/codes/python/chapter_computational_complexity/leetcode_two_sum.py @@ -4,11 +4,7 @@ Created Time: 2022-11-25 Author: Krahets (krahets@163.com) """ -import sys, os.path as osp -sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) -from modules import * - -def two_sum_brute_force(nums: List[int], target: int) -> List[int]: +def two_sum_brute_force(nums: list[int], target: int) -> list[int]: """ 方法一:暴力枚举 """ # 两层循环,时间复杂度 O(n^2) for i in range(len(nums) - 1): @@ -17,7 +13,7 @@ def two_sum_brute_force(nums: List[int], target: int) -> List[int]: return [i, j] return [] -def two_sum_hash_table(nums: List[int], target: int) -> List[int]: +def two_sum_hash_table(nums: list[int], target: int) -> list[int]: """ 方法二:辅助哈希表 """ # 辅助哈希表,空间复杂度 O(n) dic = {} @@ -37,8 +33,8 @@ if __name__ == '__main__': # ====== Driver Code ====== # 方法一 - res: List[int] = two_sum_brute_force(nums, target) + res: list[int] = two_sum_brute_force(nums, target) print("方法一 res =", res) # 方法二 - res: List[int] = two_sum_hash_table(nums, target) + res: list[int] = two_sum_hash_table(nums, target) print("方法二 res =", res) diff --git a/codes/python/chapter_computational_complexity/space_complexity.py b/codes/python/chapter_computational_complexity/space_complexity.py index be3b87bcc..f6f439009 100644 --- a/codes/python/chapter_computational_complexity/space_complexity.py +++ b/codes/python/chapter_computational_complexity/space_complexity.py @@ -17,7 +17,7 @@ def constant(n: int) -> None: """ 常数阶 """ # 常量、变量、对象占用 O(1) 空间 a: int = 0 - nums: List[int] = [0] * 10000 + nums: list[int] = [0] * 10000 node = ListNode(0) # 循环中的变量占用 O(1) 空间 for _ in range(n): @@ -29,9 +29,9 @@ def constant(n: int) -> None: def linear(n: int) -> None: """ 线性阶 """ # 长度为 n 的列表占用 O(n) 空间 - nums: List[int] = [0] * n + nums: list[int] = [0] * n # 长度为 n 的哈希表占用 O(n) 空间 - mapp: Dict = {} + mapp = dict[int, str]() for i in range(n): mapp[i] = str(i) @@ -44,16 +44,16 @@ def linear_recur(n: int) -> None: def quadratic(n: int) -> None: """ 平方阶 """ # 二维列表占用 O(n^2) 空间 - num_matrix: List[List[int]] = [[0] * n for _ in range(n)] + num_matrix: list[list[int]] = [[0] * n for _ in range(n)] def quadratic_recur(n: int) -> int: """ 平方阶(递归实现) """ if n <= 0: return 0 # 数组 nums 长度为 n, n-1, ..., 2, 1 - nums: List[int] = [0] * n + nums: list[int] = [0] * n return quadratic_recur(n - 1) -def build_tree(n: int) -> Optional[TreeNode]: +def build_tree(n: int) -> TreeNode | None: """ 指数阶(建立满二叉树) """ if n == 0: return None root = TreeNode(0) @@ -74,5 +74,5 @@ if __name__ == "__main__": quadratic(n) quadratic_recur(n) # 指数阶 - root: Optional[TreeNode] = build_tree(n) + root = build_tree(n) print_tree(root) diff --git a/codes/python/chapter_computational_complexity/time_complexity.py b/codes/python/chapter_computational_complexity/time_complexity.py index 7ef88f05d..d32969899 100644 --- a/codes/python/chapter_computational_complexity/time_complexity.py +++ b/codes/python/chapter_computational_complexity/time_complexity.py @@ -4,10 +4,6 @@ Created Time: 2022-11-25 Author: Krahets (krahets@163.com) """ -import sys, os.path as osp -sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) -from modules import * - def constant(n: int) -> int: """ 常数阶 """ count: int = 0 @@ -23,7 +19,7 @@ def linear(n: int) -> int: count += 1 return count -def array_traversal(nums: List[int]) -> int: +def array_traversal(nums: list[int]) -> int: """ 线性阶(遍历数组)""" count: int = 0 # 循环次数与数组长度成正比 @@ -40,7 +36,7 @@ def quadratic(n: int) -> int: count += 1 return count -def bubble_sort(nums: List[int]) -> int: +def bubble_sort(nums: list[int]) -> int: """ 平方阶(冒泡排序)""" count: int = 0 # 计数器 # 外循环:待排序元素数量为 n-1, n-2, ..., 1 @@ -120,7 +116,7 @@ if __name__ == "__main__": count: int = quadratic(n) print("平方阶的计算操作数量 =", count) - nums: List[int] = [i for i in range(n, 0, -1)] # [n,n-1,...,2,1] + nums: list[int] = [i for i in range(n, 0, -1)] # [n,n-1,...,2,1] count: int = bubble_sort(nums) print("平方阶(冒泡排序)的计算操作数量 =", count) diff --git a/codes/python/chapter_computational_complexity/worst_best_time_complexity.py b/codes/python/chapter_computational_complexity/worst_best_time_complexity.py index 27d1af0a7..723dccd74 100644 --- a/codes/python/chapter_computational_complexity/worst_best_time_complexity.py +++ b/codes/python/chapter_computational_complexity/worst_best_time_complexity.py @@ -4,19 +4,17 @@ Created Time: 2022-11-25 Author: Krahets (krahets@163.com) """ -import sys, os.path as osp -sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) -from modules import * +import random -def random_numbers(n: int) -> List[int]: +def random_numbers(n: int) -> list[int]: """ 生成一个数组,元素为: 1, 2, ..., n ,顺序被打乱 """ # 生成数组 nums =: 1, 2, 3, ..., n - nums: List[int] = [i for i in range(1, n + 1)] + nums: list[int] = [i for i in range(1, n + 1)] # 随机打乱数组元素 random.shuffle(nums) return nums -def find_one(nums: List[int]) -> int: +def find_one(nums: list[int]) -> int: """ 查找数组 nums 中数字 1 所在索引 """ for i in range(len(nums)): # 当元素 1 在数组头部时,达到最佳时间复杂度 O(1) @@ -30,7 +28,7 @@ def find_one(nums: List[int]) -> int: if __name__ == "__main__": for i in range(10): n: int = 100 - nums: List[int] = random_numbers(n) + nums: list[int] = random_numbers(n) index: int = find_one(nums) print("\n数组 [ 1, 2, ..., n ] 被打乱后 =", nums) print("数字 1 的索引为", index) diff --git a/codes/python/chapter_graph/graph_adjacency_list.py b/codes/python/chapter_graph/graph_adjacency_list.py index 8b67bb081..aa60a1284 100644 --- a/codes/python/chapter_graph/graph_adjacency_list.py +++ b/codes/python/chapter_graph/graph_adjacency_list.py @@ -10,10 +10,10 @@ from modules import * class GraphAdjList: """ 基于邻接表实现的无向图类 """ - def __init__(self, edges: List[List[Vertex]]) -> None: + def __init__(self, edges: list[list[Vertex]]) -> None: """ 构造方法 """ # 邻接表,key: 顶点,value:该顶点的所有邻接顶点 - self.adj_list: Dict = {} + self.adj_list = dict[Vertex, Vertex]() # 添加所有顶点和边 for edge in edges: self.add_vertex(edge[0]) diff --git a/codes/python/chapter_graph/graph_adjacency_matrix.py b/codes/python/chapter_graph/graph_adjacency_matrix.py index 838e0e1bf..c2f68e2b5 100644 --- a/codes/python/chapter_graph/graph_adjacency_matrix.py +++ b/codes/python/chapter_graph/graph_adjacency_matrix.py @@ -11,14 +11,14 @@ from modules import * class GraphAdjMat: """ 基于邻接矩阵实现的无向图类 """ # 顶点列表,元素代表“顶点值”,索引代表“顶点索引” - vertices: List[int] = [] + vertices: list[int] = [] # 邻接矩阵,行列索引对应“顶点索引” - adj_mat: List[List[int]] = [] + adj_mat: list[list[int]] = [] - def __init__(self, vertices: List[int], edges: List[List[int]]) -> None: + def __init__(self, vertices: list[int], edges: list[list[int]]) -> None: """ 构造方法 """ - self.vertices: List[int] = [] - self.adj_mat: List[List[int]] = [] + self.vertices: list[int] = [] + self.adj_mat: list[list[int]] = [] # 添加顶点 for val in vertices: self.add_vertex(val) @@ -85,8 +85,8 @@ class GraphAdjMat: if __name__ == "__main__": """ 初始化无向图 """ # 请注意,edges 元素代表顶点索引,即对应 vertices 元素索引 - vertices: List[int] = [1, 3, 2, 5, 4] - edges: List[List[int]] = [[0, 1], [0, 3], [1, 2], [2, 3], [2, 4], [3, 4]] + vertices: list[int] = [1, 3, 2, 5, 4] + edges: list[list[int]] = [[0, 1], [0, 3], [1, 2], [2, 3], [2, 4], [3, 4]] graph = GraphAdjMat(vertices, edges) print("\n初始化后,图为") graph.print() diff --git a/codes/python/chapter_graph/graph_bfs.py b/codes/python/chapter_graph/graph_bfs.py index 640c49db1..b3d8dd222 100644 --- a/codes/python/chapter_graph/graph_bfs.py +++ b/codes/python/chapter_graph/graph_bfs.py @@ -7,17 +7,18 @@ Author: Krahets (krahets@163.com) import sys, os.path as osp sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) from modules import * +from collections import deque from graph_adjacency_list import GraphAdjList -def graph_bfs(graph: GraphAdjList, start_vet: Vertex) -> List[Vertex]: +def graph_bfs(graph: GraphAdjList, start_vet: Vertex) -> list[Vertex]: """ 广度优先遍历 BFS """ # 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点 # 顶点遍历序列 res = [] # 哈希表,用于记录已被访问过的顶点 - visited = set([start_vet]) + visited = set[Vertex]([start_vet]) # 队列用于实现 BFS - que = collections.deque([start_vet]) + que = deque[Vertex]([start_vet]) # 以顶点 vet 为起点,循环直至访问完所有顶点 while len(que) > 0: vet = que.popleft() # 队首顶点出队 diff --git a/codes/python/chapter_graph/graph_dfs.py b/codes/python/chapter_graph/graph_dfs.py index f4621abce..5152c4318 100644 --- a/codes/python/chapter_graph/graph_dfs.py +++ b/codes/python/chapter_graph/graph_dfs.py @@ -9,7 +9,7 @@ sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) from modules import * from graph_adjacency_list import GraphAdjList -def dfs(graph: GraphAdjList, visited: Set[Vertex], res: List[Vertex], vet: Vertex): +def dfs(graph: GraphAdjList, visited: set[Vertex], res: list[Vertex], vet: Vertex): """ 深度优先遍历 DFS 辅助函数 """ res.append(vet) # 记录访问顶点 visited.add(vet) # 标记该顶点已被访问 @@ -21,12 +21,12 @@ def dfs(graph: GraphAdjList, visited: Set[Vertex], res: List[Vertex], vet: Verte dfs(graph, visited, res, adjVet) # 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点 -def graph_dfs(graph: GraphAdjList, start_vet: Vertex) -> List[Vertex]: +def graph_dfs(graph: GraphAdjList, start_vet: Vertex) -> list[Vertex]: """ 深度优先遍历 DFS """ # 顶点遍历序列 res = [] # 哈希表,用于记录已被访问过的顶点 - visited = set() + visited = set[Vertex]() dfs(graph, visited, res, start_vet) return res diff --git a/codes/python/chapter_hashing/array_hash_map.py b/codes/python/chapter_hashing/array_hash_map.py index 1a2cbe87d..a8609f672 100644 --- a/codes/python/chapter_hashing/array_hash_map.py +++ b/codes/python/chapter_hashing/array_hash_map.py @@ -4,10 +4,6 @@ Created Time: 2022-12-14 Author: msk397 (machangxinq@gmail.com) """ -import sys, os.path as osp -sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) -from modules import * - class Entry: """ 键值对 int->String """ def __init__(self, key: int, val: str): @@ -19,7 +15,7 @@ class ArrayHashMap: def __init__(self): """ 构造方法 """ # 初始化数组,包含 100 个桶 - self.buckets: List[Optional[Entry]] = [None] * 100 + self.buckets: list[Entry | None] = [None] * 100 def hash_func(self, key: int) -> int: """ 哈希函数 """ @@ -46,25 +42,25 @@ class ArrayHashMap: # 置为 None ,代表删除 self.buckets[index] = None - def entry_set(self) -> List[Entry]: + def entry_set(self) -> list[Entry]: """ 获取所有键值对 """ - result: List[Entry] = [] + result: list[Entry] = [] for pair in self.buckets: if pair is not None: result.append(pair) return result - def key_set(self) -> List[int]: + def key_set(self) -> list[int]: """ 获取所有键 """ - result: List[int] = [] + result: list[int] = [] for pair in self.buckets: if pair is not None: result.append(pair.key) return result - def value_set(self) -> List[str]: + def value_set(self) -> list[str]: """ 获取所有值 """ - result: List[str] = [] + result: list[str] = [] for pair in self.buckets: if pair is not None: result.append(pair.val) diff --git a/codes/python/chapter_hashing/hash_map.py b/codes/python/chapter_hashing/hash_map.py index 47005455c..5b57fd713 100644 --- a/codes/python/chapter_hashing/hash_map.py +++ b/codes/python/chapter_hashing/hash_map.py @@ -8,11 +8,10 @@ import sys, os.path as osp sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) from modules import * - """ Driver Code """ if __name__ == "__main__": """ 初始化哈希表 """ - mapp: Dict = {} + mapp = dict[int, str]() """ 添加操作 """ # 在哈希表中添加键值对 (key, value) diff --git a/codes/python/chapter_heap/heap.py b/codes/python/chapter_heap/heap.py index b0147aaa0..57875b387 100644 --- a/codes/python/chapter_heap/heap.py +++ b/codes/python/chapter_heap/heap.py @@ -4,18 +4,19 @@ Created Time: 2023-02-23 Author: Krahets (krahets@163.com) """ -import sys -import os.path as osp +import sys, os.path as osp sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) from modules import * +import heapq -def test_push(heap: List, val: int, flag: int = 1) -> None: + +def test_push(heap: list, val: int, flag: int = 1) -> None: heapq.heappush(heap, flag * val) # 元素入堆 print(f"\n元素 {val} 入堆后") print_heap([flag * val for val in heap]) -def test_pop(heap: List, flag: int = 1) -> None: +def test_pop(heap: list, flag: int = 1) -> None: val = flag * heapq.heappop(heap) # 堆顶元素出堆 print(f"\n堆顶元素 {val} 出堆后") print_heap([flag * val for val in heap]) @@ -59,7 +60,7 @@ if __name__ == "__main__": """ 输入列表并建堆 """ # 时间复杂度为 O(n) ,而非 O(nlogn) - min_heap: List[int] = [1, 3, 2, 5, 4] + min_heap: list[int] = [1, 3, 2, 5, 4] heapq.heapify(min_heap) print("\n输入列表并建立小顶堆后") print_heap(min_heap) diff --git a/codes/python/chapter_heap/my_heap.py b/codes/python/chapter_heap/my_heap.py index 3d1557759..3bc5d337b 100644 --- a/codes/python/chapter_heap/my_heap.py +++ b/codes/python/chapter_heap/my_heap.py @@ -10,7 +10,7 @@ from modules import * class MaxHeap: """ 大顶堆 """ - def __init__(self, nums: List[int]): + def __init__(self, nums: list[int]): """ 构造方法 """ # 将列表元素原封不动添加进堆 self.max_heap = nums diff --git a/codes/python/chapter_searching/binary_search.py b/codes/python/chapter_searching/binary_search.py index a481d3678..4724284cd 100644 --- a/codes/python/chapter_searching/binary_search.py +++ b/codes/python/chapter_searching/binary_search.py @@ -4,11 +4,7 @@ Created Time: 2022-11-26 Author: timi (xisunyy@163.com) """ -import sys, os.path as osp -sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) -from modules import * - -def binary_search(nums: List[int], target: int) -> int: +def binary_search(nums: list[int], target: int) -> int: """ 二分查找(双闭区间) """ # 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素 i, j = 0, len(nums) - 1 @@ -23,7 +19,7 @@ def binary_search(nums: List[int], target: int) -> int: return -1 # 未找到目标元素,返回 -1 -def binary_search1(nums: List[int], target: int) -> int: +def binary_search1(nums: list[int], target: int) -> int: """ 二分查找(左闭右开) """ # 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1 i, j = 0, len(nums) @@ -42,7 +38,7 @@ def binary_search1(nums: List[int], target: int) -> int: """ Driver Code """ if __name__ == '__main__': target: int = 6 - nums: List[int] = [1, 3, 6, 8, 12, 15, 23, 67, 70, 92] + nums: list[int] = [1, 3, 6, 8, 12, 15, 23, 67, 70, 92] # 二分查找(双闭区间) index: int = binary_search(nums, target) diff --git a/codes/python/chapter_searching/hashing_search.py b/codes/python/chapter_searching/hashing_search.py index a178180d7..96d80761e 100644 --- a/codes/python/chapter_searching/hashing_search.py +++ b/codes/python/chapter_searching/hashing_search.py @@ -8,13 +8,13 @@ import sys, os.path as osp sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) from modules import * -def hashing_search_array(mapp: Dict[int, int], target: int) -> int: +def hashing_search_array(mapp: dict[int, int], target: int) -> int: """ 哈希查找(数组) """ # 哈希表的 key: 目标元素,value: 索引 # 若哈希表中无此 key ,返回 -1 return mapp.get(target, -1) -def hashing_search_linkedlist(mapp: Dict[int, ListNode], target: int) -> Optional[ListNode]: +def hashing_search_linkedlist(mapp: dict[int, ListNode], target: int) -> ListNode | None: """ 哈希查找(链表) """ # 哈希表的 key: 目标元素,value: 结点对象 # 若哈希表中无此 key ,返回 None @@ -26,18 +26,18 @@ if __name__ == '__main__': target: int = 3 # 哈希查找(数组) - nums: List[int] = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8] + nums: list[int] = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8] # 初始化哈希表 - mapp: Dict[int, int] = {} + map0 = dict[int, int]() for i in range(len(nums)): - mapp[nums[i]] = i # key: 元素,value: 索引 - index: int = hashing_search_array(mapp, target) + map0[nums[i]] = i # key: 元素,value: 索引 + index: int = hashing_search_array(map0, target) print("目标元素 3 的索引 =", index) # 哈希查找(链表) head: ListNode = list_to_linked_list(nums) # 初始化哈希表 - map1: Dict[int, ListNode] = {} + map1 = dict[int, ListNode]() while head: map1[head.val] = head # key: 结点值,value: 结点 head = head.next diff --git a/codes/python/chapter_searching/linear_search.py b/codes/python/chapter_searching/linear_search.py index 4a97ef028..c6fb228f7 100644 --- a/codes/python/chapter_searching/linear_search.py +++ b/codes/python/chapter_searching/linear_search.py @@ -8,7 +8,7 @@ import sys, os.path as osp sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) from modules import * -def linear_search_array(nums: List[int], target: int) -> int: +def linear_search_array(nums: list[int], target: int) -> int: """ 线性查找(数组) """ # 遍历数组 for i in range(len(nums)): @@ -16,7 +16,7 @@ def linear_search_array(nums: List[int], target: int) -> int: return i return -1 # 未找到目标元素,返回 -1 -def linear_search_linkedlist(head: ListNode, target: int) -> Optional[ListNode]: +def linear_search_linkedlist(head: ListNode, target: int) -> ListNode | None: """ 线性查找(链表) """ # 遍历链表 while head: @@ -31,11 +31,11 @@ if __name__ == '__main__': target: int = 3 # 在数组中执行线性查找 - nums: List[int] = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8] + nums: list[int] = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8] index: int = linear_search_array(nums, target) print("目标元素 3 的索引 =", index) # 在链表中执行线性查找 head: ListNode = list_to_linked_list(nums) - node: Optional[ListNode] = linear_search_linkedlist(head, target) + node: ListNode | None = linear_search_linkedlist(head, target) print("目标结点值 3 的对应结点对象为", node) diff --git a/codes/python/chapter_sorting/bubble_sort.py b/codes/python/chapter_sorting/bubble_sort.py index 65b1b49a5..0bd936980 100644 --- a/codes/python/chapter_sorting/bubble_sort.py +++ b/codes/python/chapter_sorting/bubble_sort.py @@ -4,11 +4,7 @@ Created Time: 2022-11-25 Author: timi (xisunyy@163.com) """ -import sys, os.path as osp -sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) -from modules import * - -def bubble_sort(nums: List[int]) -> None: +def bubble_sort(nums: list[int]) -> None: """ 冒泡排序 """ n: int = len(nums) # 外循环:待排序元素数量为 n-1, n-2, ..., 1 @@ -19,7 +15,7 @@ def bubble_sort(nums: List[int]) -> None: # 交换 nums[j] 与 nums[j + 1] nums[j], nums[j + 1] = nums[j + 1], nums[j] -def bubble_sort_with_flag(nums: List[int]) -> None: +def bubble_sort_with_flag(nums: list[int]) -> None: """ 冒泡排序(标志优化) """ n: int = len(nums) # 外循环:待排序元素数量为 n-1, n-2, ..., 1 @@ -37,10 +33,10 @@ def bubble_sort_with_flag(nums: List[int]) -> None: """ Driver Code """ if __name__ == '__main__': - nums: List[int] = [4, 1, 3, 1, 5, 2] + nums: list[int] = [4, 1, 3, 1, 5, 2] bubble_sort(nums) print("排序后数组 nums =", nums) - nums1: List[int] = [4, 1, 3, 1, 5, 2] + nums1: list[int] = [4, 1, 3, 1, 5, 2] bubble_sort_with_flag(nums1) print("排序后数组 nums =", nums1) diff --git a/codes/python/chapter_sorting/counting_sort.py b/codes/python/chapter_sorting/counting_sort.py index 64be8e2fd..baca22d4d 100644 --- a/codes/python/chapter_sorting/counting_sort.py +++ b/codes/python/chapter_sorting/counting_sort.py @@ -4,11 +4,7 @@ Created Time: 2023-03-21 Author: Krahets (krahets@163.com) """ -import sys, os.path as osp -sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) -from modules import * - -def counting_sort_naive(nums: List[int]) -> None: +def counting_sort_naive(nums: list[int]) -> None: """ 计数排序 """ # 简单实现,无法用于排序对象 # 1. 统计数组最大元素 m @@ -27,7 +23,7 @@ def counting_sort_naive(nums: List[int]) -> None: nums[i] = num i += 1 -def counting_sort(nums: List[int]) -> None: +def counting_sort(nums: list[int]) -> None: """ 计数排序 """ # 完整实现,可排序对象,并且是稳定排序 # 1. 统计数组最大元素 m diff --git a/codes/python/chapter_sorting/insertion_sort.py b/codes/python/chapter_sorting/insertion_sort.py index 062308015..fcb59f02f 100644 --- a/codes/python/chapter_sorting/insertion_sort.py +++ b/codes/python/chapter_sorting/insertion_sort.py @@ -4,11 +4,7 @@ Created Time: 2022-11-25 Author: timi (xisunyy@163.com) """ -import sys, os.path as osp -sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) -from modules import * - -def insertion_sort(nums: List[int]) -> None: +def insertion_sort(nums: list[int]) -> None: """ 插入排序 """ # 外循环:base = nums[1], nums[2], ..., nums[n-1] for i in range(1, len(nums)): @@ -23,6 +19,6 @@ def insertion_sort(nums: List[int]) -> None: """ Driver Code """ if __name__ == '__main__': - nums: List[int] = [4, 1, 3, 1, 5, 2] + nums: list[int] = [4, 1, 3, 1, 5, 2] insertion_sort(nums) print("排序后数组 nums =", nums) diff --git a/codes/python/chapter_sorting/merge_sort.py b/codes/python/chapter_sorting/merge_sort.py index 15ed8e9d3..135274aff 100644 --- a/codes/python/chapter_sorting/merge_sort.py +++ b/codes/python/chapter_sorting/merge_sort.py @@ -4,16 +4,12 @@ Created Time: 2022-11-25 Author: timi (xisunyy@163.com) """ -import sys, os.path as osp -sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) -from modules import * - -def merge(nums: List[int], left: int, mid: int, right: int) -> None: +def merge(nums: list[int], left: int, mid: int, right: int) -> None: """ 合并左子数组和右子数组 """ # 左子数组区间 [left, mid] # 右子数组区间 [mid + 1, right] - # 初始化辅助数组 借助 copy模块 - tmp: List[int] = nums[left:right + 1].copy() + # 初始化辅助数组 + tmp: list[int] = list(nums[left:right + 1]) # 左子数组的起始索引和结束索引 left_start: int = 0 left_end: int = mid - left @@ -38,7 +34,7 @@ def merge(nums: List[int], left: int, mid: int, right: int) -> None: nums[k] = tmp[j] j += 1 -def merge_sort(nums: List[int], left: int, right: int) -> None: +def merge_sort(nums: list[int], left: int, right: int) -> None: """ 归并排序 """ # 终止条件 if left >= right: @@ -53,6 +49,6 @@ def merge_sort(nums: List[int], left: int, right: int) -> None: """ Driver Code """ if __name__ == '__main__': - nums: List[int] = [ 7, 3, 2, 6, 0, 1, 5, 4 ] + nums: list[int] = [ 7, 3, 2, 6, 0, 1, 5, 4 ] merge_sort(nums, 0, len(nums) - 1) print("归并排序完成后 nums =", nums) diff --git a/codes/python/chapter_sorting/quick_sort.py b/codes/python/chapter_sorting/quick_sort.py index 1b72d3be0..c0961c224 100644 --- a/codes/python/chapter_sorting/quick_sort.py +++ b/codes/python/chapter_sorting/quick_sort.py @@ -4,13 +4,9 @@ Created Time: 2022-11-25 Author: timi (xisunyy@163.com) """ -import sys, os.path as osp -sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) -from modules import * - class QuickSort: """ 快速排序类 """ - def partition(self, nums: List[int], left: int, right: int) -> int: + def partition(self, nums: list[int], left: int, right: int) -> int: """ 哨兵划分 """ # 以 nums[left] 作为基准数 i, j = left, right @@ -25,7 +21,7 @@ class QuickSort: nums[i], nums[left] = nums[left], nums[i] return i # 返回基准数的索引 - def quick_sort(self, nums: List[int], left: int, right: int) -> None: + def quick_sort(self, nums: list[int], left: int, right: int) -> None: """ 快速排序 """ # 子数组长度为 1 时终止递归 if left >= right: @@ -38,7 +34,7 @@ class QuickSort: class QuickSortMedian: """ 快速排序类(中位基准数优化)""" - def median_three(self, nums: List[int], left: int, mid: int, right: int) -> int: + def median_three(self, nums: list[int], left: int, mid: int, right: int) -> int: """ 选取三个元素的中位数 """ # 此处使用异或运算来简化代码 # 异或规则为 0 ^ 0 = 1 ^ 1 = 0, 0 ^ 1 = 1 ^ 0 = 1 @@ -48,7 +44,7 @@ class QuickSortMedian: return mid return right - def partition(self, nums: List[int], left: int, right: int) -> int: + def partition(self, nums: list[int], left: int, right: int) -> int: """ 哨兵划分(三数取中值) """ # 以 nums[left] 作为基准数 med: int = self.median_three(nums, left, (left + right) // 2, right) @@ -67,7 +63,7 @@ class QuickSortMedian: nums[i], nums[left] = nums[left], nums[i] return i # 返回基准数的索引 - def quick_sort(self, nums: List[int], left: int, right: int) -> None: + def quick_sort(self, nums: list[int], left: int, right: int) -> None: """ 快速排序 """ # 子数组长度为 1 时终止递归 if left >= right: @@ -80,7 +76,7 @@ class QuickSortMedian: class QuickSortTailCall: """ 快速排序类(尾递归优化) """ - def partition(self, nums: List[int], left: int, right: int) -> int: + def partition(self, nums: list[int], left: int, right: int) -> int: """ 哨兵划分 """ # 以 nums[left] 作为基准数 i, j = left, right @@ -95,7 +91,7 @@ class QuickSortTailCall: nums[i], nums[left] = nums[left], nums[i] return i # 返回基准数的索引 - def quick_sort(self, nums: List[int], left: int, right: int) -> None: + def quick_sort(self, nums: list[int], left: int, right: int) -> None: """ 快速排序(尾递归优化) """ # 子数组长度为 1 时终止 while left < right: @@ -113,16 +109,16 @@ class QuickSortTailCall: """ Driver Code """ if __name__ == '__main__': # 快速排序 - nums: List[int] = [2, 4, 1, 0, 3, 5] + nums: list[int] = [2, 4, 1, 0, 3, 5] QuickSort().quick_sort(nums, 0, len(nums) - 1) print("快速排序完成后 nums =", nums) # 快速排序(中位基准数优化) - nums1: List[int] = [2, 4, 1, 0, 3, 5] + nums1: list[int] = [2, 4, 1, 0, 3, 5] QuickSortMedian().quick_sort(nums1, 0, len(nums1) - 1) print("快速排序(中位基准数优化)完成后 nums =", nums1) # 快速排序(尾递归优化) - nums2: List[int] = [2, 4, 1, 0, 3, 5] + nums2: list[int] = [2, 4, 1, 0, 3, 5] QuickSortTailCall().quick_sort(nums2, 0, len(nums2) - 1) print("快速排序(尾递归优化)完成后 nums =", nums2) diff --git a/codes/python/chapter_stack_and_queue/array_deque.py b/codes/python/chapter_stack_and_queue/array_deque.py index df7cffe7c..36c169161 100644 --- a/codes/python/chapter_stack_and_queue/array_deque.py +++ b/codes/python/chapter_stack_and_queue/array_deque.py @@ -4,17 +4,11 @@ Created Time: 2023-03-01 Author: Krahets (krahets@163.com) """ -import sys, os.path as osp -sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) -from modules import * - - class ArrayDeque: """ 基于环形数组实现的双向队列 """ - def __init__(self, capacity: int) -> None: """ 构造方法 """ - self.__nums: List[int] = [0] * capacity + self.__nums: list[int] = [0] * capacity self.__front: int = 0 self.__size: int = 0 @@ -86,7 +80,7 @@ class ArrayDeque: last = self.index(self.__front + self.__size - 1) return self.__nums[last] - def to_array(self) -> List[int]: + def to_array(self) -> list[int]: """ 返回数组用于打印 """ # 仅转换有效长度范围内的列表元素 res = [] diff --git a/codes/python/chapter_stack_and_queue/array_queue.py b/codes/python/chapter_stack_and_queue/array_queue.py index 788a71a4b..7920def71 100644 --- a/codes/python/chapter_stack_and_queue/array_queue.py +++ b/codes/python/chapter_stack_and_queue/array_queue.py @@ -4,15 +4,11 @@ Created Time: 2022-12-01 Author: Peng Chen (pengchzn@gmail.com) """ -import sys, os.path as osp -sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) -from modules import * - class ArrayQueue: """ 基于环形数组实现的队列 """ def __init__(self, size: int) -> None: """ 构造方法 """ - self.__nums: List[int] = [0] * size # 用于存储队列元素的数组 + self.__nums: list[int] = [0] * size # 用于存储队列元素的数组 self.__front: int = 0 # 队首指针,指向队首元素 self.__size: int = 0 # 队列长度 @@ -51,9 +47,9 @@ class ArrayQueue: assert not self.is_empty(), "队列为空" return self.__nums[self.__front] - def to_list(self) -> List[int]: + def to_list(self) -> list[int]: """ 返回列表用于打印 """ - res: List[int] = [0] * self.size() + res: list[int] = [0] * self.size() j: int = self.__front for i in range(self.size()): res[i] = self.__nums[(j % self.capacity())] diff --git a/codes/python/chapter_stack_and_queue/array_stack.py b/codes/python/chapter_stack_and_queue/array_stack.py index a6888b6c5..7fe3af4c5 100644 --- a/codes/python/chapter_stack_and_queue/array_stack.py +++ b/codes/python/chapter_stack_and_queue/array_stack.py @@ -4,15 +4,11 @@ Created Time: 2022-11-29 Author: Peng Chen (pengchzn@gmail.com) """ -import sys, os.path as osp -sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) -from modules import * - class ArrayStack: """ 基于数组实现的栈 """ def __init__(self) -> None: """ 构造方法 """ - self.__stack: List[int] = [] + self.__stack: list[int] = [] def size(self) -> int: """ 获取栈的长度 """ @@ -36,7 +32,7 @@ class ArrayStack: assert not self.is_empty(), "栈为空" return self.__stack[-1] - def to_list(self) -> List[int]: + def to_list(self) -> list[int]: """ 返回列表用于打印 """ return self.__stack diff --git a/codes/python/chapter_stack_and_queue/deque.py b/codes/python/chapter_stack_and_queue/deque.py index 6a4c3a31e..67df57c24 100644 --- a/codes/python/chapter_stack_and_queue/deque.py +++ b/codes/python/chapter_stack_and_queue/deque.py @@ -4,42 +4,39 @@ Created Time: 2022-11-29 Author: Peng Chen (pengchzn@gmail.com) """ -import sys, os.path as osp -sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) -from modules import * - +from collections import deque """ Driver Code """ if __name__ == "__main__": """ 初始化双向队列 """ - deque: Deque[int] = collections.deque() + deq: deque[int] = deque() """ 元素入队 """ - deque.append(2) # 添加至队尾 - deque.append(5) - deque.append(4) - deque.appendleft(3) # 添加至队首 - deque.appendleft(1) - print("双向队列 deque =", deque) + deq.append(2) # 添加至队尾 + deq.append(5) + deq.append(4) + deq.appendleft(3) # 添加至队首 + deq.appendleft(1) + print("双向队列 deque =", deq) """ 访问元素 """ - front: int = deque[0] # 队首元素 + front: int = deq[0] # 队首元素 print("队首元素 front =", front) - rear: int = deque[-1] # 队尾元素 + rear: int = deq[-1] # 队尾元素 print("队尾元素 rear =", rear) """ 元素出队 """ - pop_front: int = deque.popleft() # 队首元素出队 + pop_front: int = deq.popleft() # 队首元素出队 print("队首出队元素 pop_front =", pop_front) - print("队首出队后 deque =", deque) - pop_rear: int = deque.pop() # 队尾元素出队 + print("队首出队后 deque =", deq) + pop_rear: int = deq.pop() # 队尾元素出队 print("队尾出队元素 pop_rear =", pop_rear) - print("队尾出队后 deque =", deque) + print("队尾出队后 deque =", deq) """ 获取双向队列的长度 """ - size: int = len(deque) + size: int = len(deq) print("双向队列长度 size =", size) """ 判断双向队列是否为空 """ - is_empty: bool = len(deque) == 0 + is_empty: bool = len(deq) == 0 print("双向队列是否为空 =", is_empty) diff --git a/codes/python/chapter_stack_and_queue/linkedlist_deque.py b/codes/python/chapter_stack_and_queue/linkedlist_deque.py index a6d7c1f12..0d63ab4fb 100644 --- a/codes/python/chapter_stack_and_queue/linkedlist_deque.py +++ b/codes/python/chapter_stack_and_queue/linkedlist_deque.py @@ -4,24 +4,20 @@ Created Time: 2023-03-01 Author: Krahets (krahets@163.com) """ -import sys, os.path as osp -sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) -from modules import * - class ListNode: """ 双向链表结点 """ def __init__(self, val: int) -> None: """ 构造方法 """ self.val: int = val - self.next: Optional[ListNode] = None # 后继结点引用(指针) - self.prev: Optional[ListNode] = None # 前驱结点引用(指针) + self.next: ListNode | None = None # 后继结点引用(指针) + self.prev: ListNode | None = None # 前驱结点引用(指针) class LinkedListDeque: """ 基于双向链表实现的双向队列 """ def __init__(self) -> None: """ 构造方法 """ - self.front: Optional[ListNode] = None # 头结点 front - self.rear: Optional[ListNode] = None # 尾结点 rear + self.front: ListNode | None = None # 头结点 front + self.rear: ListNode | None = None # 尾结点 rear self.__size: int = 0 # 双向队列的长度 def size(self) -> int: @@ -69,7 +65,7 @@ class LinkedListDeque: if is_front: val: int = self.front.val # 暂存头结点值 # 删除头结点 - fnext: Optional[ListNode] = self.front.next + fnext: ListNode | None = self.front.next if fnext != None: fnext.prev = None self.front.next = None @@ -78,7 +74,7 @@ class LinkedListDeque: else: val: int = self.rear.val # 暂存尾结点值 # 删除尾结点 - rprev: Optional[ListNode] = self.rear.prev + rprev: ListNode | None = self.rear.prev if rprev != None: rprev.next = None self.rear.prev = None @@ -102,10 +98,10 @@ class LinkedListDeque: """ 访问队尾元素 """ return None if self.is_empty() else self.rear.val - def to_array(self) -> List[int]: + def to_array(self) -> list[int]: """ 返回数组用于打印 """ - node: Optional[ListNode] = self.front - res: List[int] = [0] * self.size() + node: ListNode | None = self.front + res: list[int] = [0] * self.size() for i in range(self.size()): res[i] = node.val node = node.next diff --git a/codes/python/chapter_stack_and_queue/linkedlist_queue.py b/codes/python/chapter_stack_and_queue/linkedlist_queue.py index 50f9a431d..793339d33 100644 --- a/codes/python/chapter_stack_and_queue/linkedlist_queue.py +++ b/codes/python/chapter_stack_and_queue/linkedlist_queue.py @@ -12,8 +12,8 @@ class LinkedListQueue: """ 基于链表实现的队列 """ def __init__(self): """ 构造方法 """ - self.__front: Optional[ListNode] = None # 头结点 front - self.__rear: Optional[ListNode] = None # 尾结点 rear + self.__front: ListNode | None = None # 头结点 front + self.__rear: ListNode | None = None # 尾结点 rear self.__size: int = 0 def size(self) -> int: @@ -53,7 +53,7 @@ class LinkedListQueue: return False return self.__front.val - def to_list(self) -> List[int]: + def to_list(self) -> list[int]: """ 转化为列表用于打印 """ queue = [] temp = self.__front diff --git a/codes/python/chapter_stack_and_queue/linkedlist_stack.py b/codes/python/chapter_stack_and_queue/linkedlist_stack.py index 0255050d1..0c35451ac 100644 --- a/codes/python/chapter_stack_and_queue/linkedlist_stack.py +++ b/codes/python/chapter_stack_and_queue/linkedlist_stack.py @@ -12,7 +12,7 @@ class LinkedListStack: """ 基于链表实现的栈 """ def __init__(self): """ 构造方法 """ - self.__peek: Optional[ListNode] = None + self.__peek: ListNode | None = None self.__size: int = 0 def size(self) -> int: @@ -43,9 +43,9 @@ class LinkedListStack: if not self.__peek: return None return self.__peek.val - def to_list(self) -> List[int]: + def to_list(self) -> list[int]: """ 转化为列表用于打印 """ - arr: List[int] = [] + arr: list[int] = [] node = self.__peek while node: arr.append(node.val) diff --git a/codes/python/chapter_stack_and_queue/queue.py b/codes/python/chapter_stack_and_queue/queue.py index 20fb28437..43bbfe037 100644 --- a/codes/python/chapter_stack_and_queue/queue.py +++ b/codes/python/chapter_stack_and_queue/queue.py @@ -4,17 +4,15 @@ Created Time: 2022-11-29 Author: Peng Chen (pengchzn@gmail.com) """ -import sys, os.path as osp -sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) -from modules import * - +from collections import deque """ Driver Code """ -if __name__ == "__main__": +if __name__ == "__main__": + """ 初始化队列 """ # 在 Python 中,我们一般将双向队列类 deque 看作队列使用 # 虽然 queue.Queue() 是纯正的队列类,但不太好用 - que: Deque[int] = collections.deque() + que: deque[int] = deque() """ 元素入队 """ que.append(1) diff --git a/codes/python/chapter_stack_and_queue/stack.py b/codes/python/chapter_stack_and_queue/stack.py index 0a65a2e84..b6bbc6210 100644 --- a/codes/python/chapter_stack_and_queue/stack.py +++ b/codes/python/chapter_stack_and_queue/stack.py @@ -4,16 +4,11 @@ Created Time: 2022-11-29 Author: Peng Chen (pengchzn@gmail.com) """ -import sys, os.path as osp -sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) -from modules import * - - """ Driver Code """ if __name__ == "__main__": """ 初始化栈 """ # Python 没有内置的栈类,可以把 list 当作栈来使用 - stack: List[int] = [] + stack: list[int] = [] """ 元素入栈 """ stack.append(1) diff --git a/codes/python/chapter_tree/avl_tree.py b/codes/python/chapter_tree/avl_tree.py index 2911270c4..76213e62a 100644 --- a/codes/python/chapter_tree/avl_tree.py +++ b/codes/python/chapter_tree/avl_tree.py @@ -10,27 +10,27 @@ from modules import * class AVLTree: """ AVL 树 """ - def __init__(self, root: Optional[TreeNode] = None): + def __init__(self, root: TreeNode | None = None): """ 构造方法 """ self.__root = root @property - def root(self) -> Optional[TreeNode]: + def root(self) -> TreeNode | None: return self.__root - def height(self, node: Optional[TreeNode]) -> int: + def height(self, node: TreeNode | None) -> int: """ 获取结点高度 """ # 空结点高度为 -1 ,叶结点高度为 0 if node is not None: return node.height return -1 - def __update_height(self, node: Optional[TreeNode]): + def __update_height(self, node: TreeNode | None): """ 更新结点高度 """ # 结点高度等于最高子树高度 + 1 node.height = max([self.height(node.left), self.height(node.right)]) + 1 - def balance_factor(self, node: Optional[TreeNode]) -> int: + def balance_factor(self, node: TreeNode | None) -> int: """ 获取平衡因子 """ # 空结点平衡因子为 0 if node is None: @@ -38,7 +38,7 @@ class AVLTree: # 结点平衡因子 = 左子树高度 - 右子树高度 return self.height(node.left) - self.height(node.right) - def __right_rotate(self, node: Optional[TreeNode]) -> Optional[TreeNode]: + def __right_rotate(self, node: TreeNode | None) -> TreeNode | None: """ 右旋操作 """ child = node.left grand_child = child.right @@ -51,7 +51,7 @@ class AVLTree: # 返回旋转后子树的根结点 return child - def __left_rotate(self, node: Optional[TreeNode]) -> Optional[TreeNode]: + def __left_rotate(self, node: TreeNode | None) -> TreeNode | None: """ 左旋操作 """ child = node.right grand_child = child.left @@ -64,7 +64,7 @@ class AVLTree: # 返回旋转后子树的根结点 return child - def __rotate(self, node: Optional[TreeNode]) -> Optional[TreeNode]: + def __rotate(self, node: TreeNode | None) -> TreeNode | None: """ 执行旋转操作,使该子树重新恢复平衡 """ # 获取结点 node 的平衡因子 balance_factor = self.balance_factor(node) @@ -94,7 +94,7 @@ class AVLTree: self.__root = self.__insert_helper(self.__root, val) return self.__root - def __insert_helper(self, node: Optional[TreeNode], val: int) -> TreeNode: + def __insert_helper(self, node: TreeNode | None, val: int) -> TreeNode: """ 递归插入结点(辅助方法)""" if node is None: return TreeNode(val) @@ -111,12 +111,12 @@ class AVLTree: # 2. 执行旋转操作,使该子树重新恢复平衡 return self.__rotate(node) - def remove(self, val: int) -> Optional[TreeNode]: + def remove(self, val: int) -> TreeNode | None: """ 删除结点 """ self.__root = self.__remove_helper(self.__root, val) return self.__root - def __remove_helper(self, node: Optional[TreeNode], val: int) -> Optional[TreeNode]: + def __remove_helper(self, node: TreeNode | None, val: int) -> TreeNode | None: """ 递归删除结点(辅助方法) """ if node is None: return None @@ -143,7 +143,7 @@ class AVLTree: # 2. 执行旋转操作,使该子树重新恢复平衡 return self.__rotate(node) - def __get_inorder_next(self, node: Optional[TreeNode]) -> Optional[TreeNode]: + def __get_inorder_next(self, node: TreeNode | None) -> TreeNode | None: """ 获取中序遍历中的下一个结点(仅适用于 root 有左子结点的情况) """ if node is None: return None @@ -152,7 +152,7 @@ class AVLTree: node = node.left return node - def search(self, val: int) -> Optional[TreeNode]: + def search(self, val: int) -> TreeNode | None: """ 查找结点 """ cur = self.__root # 循环查找,越过叶结点后跳出 diff --git a/codes/python/chapter_tree/binary_search_tree.py b/codes/python/chapter_tree/binary_search_tree.py index 27fb0536d..b87d87ff2 100644 --- a/codes/python/chapter_tree/binary_search_tree.py +++ b/codes/python/chapter_tree/binary_search_tree.py @@ -11,12 +11,12 @@ from modules import * class BinarySearchTree: """ 二叉搜索树 """ - def __init__(self, nums: List[int]) -> None: + def __init__(self, nums: list[int]) -> None: """ 构造方法 """ nums.sort() self.__root = self.build_tree(nums, 0, len(nums) - 1) - def build_tree(self, nums: List[int], start_index: int, end_index: int) -> Optional[TreeNode]: + def build_tree(self, nums: list[int], start_index: int, end_index: int) -> TreeNode | None: """ 构建二叉搜索树 """ if start_index > end_index: return None @@ -30,12 +30,12 @@ class BinarySearchTree: return root @property - def root(self) -> Optional[TreeNode]: + def root(self) -> TreeNode | None: return self.__root - def search(self, num: int) -> Optional[TreeNode]: + def search(self, num: int) -> TreeNode | None: """ 查找结点 """ - cur: Optional[TreeNode] = self.__root + cur: TreeNode | None = self.__root # 循环查找,越过叶结点后跳出 while cur is not None: # 目标结点在 cur 的右子树中 @@ -49,7 +49,7 @@ class BinarySearchTree: break return cur - def insert(self, num: int) -> Optional[TreeNode]: + def insert(self, num: int) -> TreeNode | None: """ 插入结点 """ # 若树为空,直接提前返回 if self.__root is None: @@ -77,7 +77,7 @@ class BinarySearchTree: pre.left = node return node - def remove(self, num: int) -> Optional[TreeNode]: + def remove(self, num: int) -> TreeNode | None: """ 删除结点 """ # 若树为空,直接提前返回 if self.__root is None: @@ -118,7 +118,7 @@ class BinarySearchTree: cur.val = tmp return cur - def get_inorder_next(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + def get_inorder_next(self, root: TreeNode | None) -> TreeNode | None: """ 获取中序遍历中的下一个结点(仅适用于 root 有左子结点的情况) """ if root is None: return root diff --git a/codes/python/chapter_tree/binary_tree_bfs.py b/codes/python/chapter_tree/binary_tree_bfs.py index 408f8bf83..020387d29 100644 --- a/codes/python/chapter_tree/binary_tree_bfs.py +++ b/codes/python/chapter_tree/binary_tree_bfs.py @@ -7,15 +7,15 @@ Author: a16su (lpluls001@gmail.com) import sys, os.path as osp sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) from modules import * +from collections import deque - -def level_order(root: Optional[TreeNode]) -> List[int]: +def level_order(root: TreeNode | None) -> list[int]: """ 层序遍历 """ # 初始化队列,加入根结点 - queue: Deque[TreeNode] = collections.deque() + queue: deque[TreeNode] = deque() queue.append(root) # 初始化一个列表,用于保存遍历序列 - res: List[int] = [] + res: list[int] = [] while queue: node: TreeNode = queue.popleft() # 队列出队 res.append(node.val) # 保存结点值 @@ -35,6 +35,6 @@ if __name__ == "__main__": print_tree(root) # 层序遍历 - res: List[int] = level_order(root) + res: list[int] = level_order(root) print("\n层序遍历的结点打印序列 = ", res) assert res == [1, 2, 3, 4, 5, 6, 7] diff --git a/codes/python/chapter_tree/binary_tree_dfs.py b/codes/python/chapter_tree/binary_tree_dfs.py index 77d8b4b39..b2e0583fe 100644 --- a/codes/python/chapter_tree/binary_tree_dfs.py +++ b/codes/python/chapter_tree/binary_tree_dfs.py @@ -8,8 +8,7 @@ import sys, os.path as osp sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) from modules import * - -def pre_order(root: Optional[TreeNode]) -> None: +def pre_order(root: TreeNode | None) -> None: """ 前序遍历 """ if root is None: return @@ -18,7 +17,7 @@ def pre_order(root: Optional[TreeNode]) -> None: pre_order(root=root.left) pre_order(root=root.right) -def in_order(root: Optional[TreeNode]) -> None: +def in_order(root: TreeNode | None) -> None: """ 中序遍历 """ if root is None: return @@ -27,7 +26,7 @@ def in_order(root: Optional[TreeNode]) -> None: res.append(root.val) in_order(root=root.right) -def post_order(root: Optional[TreeNode]) -> None: +def post_order(root: TreeNode | None) -> None: """ 后序遍历 """ if root is None: return diff --git a/codes/python/modules/__init__.py b/codes/python/modules/__init__.py index a614be68f..d9519dad8 100644 --- a/codes/python/modules/__init__.py +++ b/codes/python/modules/__init__.py @@ -1,12 +1,8 @@ -import copy -import math -import heapq -import queue -import random -import functools -import collections -from typing import Optional, Tuple, List, Dict, DefaultDict, OrderedDict, Set, Deque +# Follow the PEP 585 – Type Hinting Generics In Standard Collections +# https://peps.python.org/pep-0585/ +from __future__ import annotations +# Import common libs here to simplify the codes by `from module import *` from .linked_list import ListNode, list_to_linked_list, linked_list_to_list, get_list_node -from .binary_tree import TreeNode, list_to_tree, tree_to_list, get_tree_node +from .binary_tree import TreweNode, list_to_tree, tree_to_list, get_tree_node from .vertex import Vertex, vals_to_vets, vets_to_vals -from .print_util import print_matrix, print_linked_list, print_tree, print_dict, print_heap \ No newline at end of file +from .print_util import print_matrix, print_linked_list, print_tree, print_dict, print_heap diff --git a/codes/python/modules/binary_tree.py b/codes/python/modules/binary_tree.py index fb7330752..42831be95 100644 --- a/codes/python/modules/binary_tree.py +++ b/codes/python/modules/binary_tree.py @@ -4,25 +4,24 @@ Created Time: 2021-12-11 Author: Krahets (krahets@163.com) """ -import collections -from typing import List, Deque, Optional +from collections import deque class TreeNode: """ Definition for a binary tree node """ - def __init__(self, val: int = 0, left: Optional['TreeNode'] = None, right: Optional['TreeNode'] = None): - self.val: int = val # 结点值 - self.height: int = 0 # 结点高度 - self.left: Optional[TreeNode] = left # 左子结点引用 - self.right: Optional[TreeNode] = right # 右子结点引用 + def __init__(self, val: int = 0): + self.val: int = val # 结点值 + self.height: int = 0 # 结点高度 + self.left: TreeNode | None = None # 左子结点引用 + self.right: TreeNode | None = None # 右子结点引用 -def list_to_tree(arr: List[int]) -> Optional[TreeNode]: +def list_to_tree(arr: list[int]) -> TreeNode | None: """ Generate a binary tree with a list """ if not arr: return None i: int = 0 root = TreeNode(arr[0]) - queue: Deque[TreeNode] = collections.deque([root]) + queue: deque[TreeNode] = deque([root]) while queue: node: TreeNode = queue.popleft() i += 1 @@ -38,14 +37,14 @@ def list_to_tree(arr: List[int]) -> Optional[TreeNode]: return root -def tree_to_list(root: Optional[TreeNode]) -> List[int]: +def tree_to_list(root: TreeNode | None) -> list[int]: """ Serialize a tree into an array """ if not root: return [] - queue: Deque[TreeNode] = collections.deque() + queue: deque[TreeNode] = deque() queue.append(root) - res: List[int] = [] + res: list[int] = [] while queue: - node: Optional[TreeNode] = queue.popleft() + node: TreeNode | None = queue.popleft() if node: res.append(node.val) queue.append(node.left) @@ -53,12 +52,12 @@ def tree_to_list(root: Optional[TreeNode]) -> List[int]: else: res.append(None) return res -def get_tree_node(root: Optional[TreeNode], val: int) -> Optional[TreeNode]: +def get_tree_node(root: TreeNode | None, val: int) -> TreeNode | None: """ Get a tree node with specific value in a binary tree """ if not root: return if root.val == val: return root - left: Optional[TreeNode] = get_tree_node(root.left, val) - right: Optional[TreeNode] = get_tree_node(root.right, val) + left: TreeNode | None = get_tree_node(root.left, val) + right: TreeNode | None = get_tree_node(root.right, val) return left if left else right diff --git a/codes/python/modules/linked_list.py b/codes/python/modules/linked_list.py index 6876c2fe7..6d87bd225 100644 --- a/codes/python/modules/linked_list.py +++ b/codes/python/modules/linked_list.py @@ -4,15 +4,13 @@ Created Time: 2021-12-11 Author: Krahets (krahets@163.com) """ -from typing import List, Optional - class ListNode: """ Definition for a singly-linked list node """ def __init__(self, val: int): self.val: int = val # 结点值 - self.next: Optional[ListNode] = None # 后继结点引用 + self.next: ListNode | None = None # 后继结点引用 -def list_to_linked_list(arr: List[int]) -> Optional[ListNode]: +def list_to_linked_list(arr: list[int]) -> ListNode | None: """ Generate a linked list with a list """ dum = head = ListNode(0) for a in arr: @@ -21,15 +19,15 @@ def list_to_linked_list(arr: List[int]) -> Optional[ListNode]: head = head.next return dum.next -def linked_list_to_list(head: Optional[ListNode]) -> List[int]: +def linked_list_to_list(head: ListNode | None) -> list[int]: """ Serialize a linked list into an array """ - arr: List[int] = [] + arr: list[int] = [] while head: arr.append(head.val) head = head.next return arr -def get_list_node(head: Optional[ListNode], val: int) -> Optional[ListNode]: +def get_list_node(head: ListNode | None, val: int) -> ListNode | None: """ Get a list node with specific value from a linked list """ while head and head.val != val: head = head.next diff --git a/codes/python/modules/print_util.py b/codes/python/modules/print_util.py index ffe9c03ce..d08ca961d 100644 --- a/codes/python/modules/print_util.py +++ b/codes/python/modules/print_util.py @@ -7,33 +7,31 @@ Author: Krahets (krahets@163.com), msk397 (machangxinq@gmail.com) from .binary_tree import TreeNode, list_to_tree from .linked_list import ListNode, linked_list_to_list -from typing import List, Optional, Dict - -def print_matrix(mat: List[List[int]]) -> None: +def print_matrix(mat: list[list[int]]) -> None: """ Print a matrix """ - s: List[str] = [] + s: list[str] = [] for arr in mat: s.append(' ' + str(arr)) print('[\n' + ',\n'.join(s) + '\n]') -def print_linked_list(head: Optional[ListNode]) -> None: +def print_linked_list(head: ListNode | None) -> None: """ Print a linked list """ - arr: List[int] = linked_list_to_list(head) + arr: list[int] = linked_list_to_list(head) print(' -> '.join([str(a) for a in arr])) class Trunk: - def __init__(self, prev: Optional['Trunk'] = None, string: Optional[str] = None) -> None: - self.prev: Optional[Trunk] = prev - self.str: Optional[str] = string + def __init__(self, prev, string: str | None = None) -> None: + self.prev = prev + self.str = string -def show_trunks(p: Optional[Trunk]) -> None: +def show_trunks(p: Trunk | None) -> None: if p is None: return show_trunks(p.prev) print(p.str, end='') -def print_tree(root: Optional[TreeNode], prev: Optional[Trunk] = None, is_left: bool = False) -> None: +def print_tree(root: TreeNode | None, prev: Trunk | None = None, is_left: bool = False) -> None: """ Print a binary tree This tree printer is borrowed from TECHIE DELIGHT @@ -62,14 +60,14 @@ def print_tree(root: Optional[TreeNode], prev: Optional[Trunk] = None, is_left: trunk.str = ' |' print_tree(root.left, trunk, False) -def print_dict(mapp: Dict) -> None: +def print_dict(mapp: dict) -> None: """ Print a dict """ for key, value in mapp.items(): print(key, '->', value) -def print_heap(heap: List[int]) -> None: +def print_heap(heap: list[int]) -> None: """ Print a heap both in array and tree representations """ print("堆的数组表示:", heap) print("堆的树状表示:") - root: Optional[TreeNode] = list_to_tree(heap) + root: TreeNode | None = list_to_tree(heap) print_tree(root) diff --git a/codes/python/modules/vertex.py b/codes/python/modules/vertex.py index 7f61b562f..621f6dc0b 100644 --- a/codes/python/modules/vertex.py +++ b/codes/python/modules/vertex.py @@ -2,17 +2,15 @@ # Created Time: 2023-02-23 # Author: Krahets (krahets@163.com) -from typing import List - class Vertex: """ 顶点类 """ def __init__(self, val: int) -> None: self.val = val -def vals_to_vets(vals: List[int]) -> List['Vertex']: +def vals_to_vets(vals: list[int]) -> list['Vertex']: """ 输入值列表 vals ,返回顶点列表 vets """ return [Vertex(val) for val in vals] -def vets_to_vals(vets: List['Vertex']) -> List[int]: +def vets_to_vals(vets: list['Vertex']) -> list[int]: """ 输入顶点列表 vets ,返回值列表 vals """ return [vet.val for vet in vets]