Simplify the declarations of the Python code.

This commit is contained in:
krahets 2023-05-22 22:03:57 +08:00
parent 081b76d620
commit e196962d0a
27 changed files with 88 additions and 87 deletions

View file

@ -70,9 +70,9 @@ def find(nums: list[int], target: int) -> int:
"""Driver Code"""
if __name__ == "__main__":
# 初始化数组
arr: list[int] = [0] * 5
arr = [0] * 5
print("数组 arr =", arr)
nums: list[int] = [1, 3, 2, 5, 4]
nums = [1, 3, 2, 5, 4]
print("数组 nums =", nums)
# 随机访问

View file

@ -7,7 +7,7 @@ Author: Krahets (krahets@163.com)
"""Driver Code"""
if __name__ == "__main__":
# 初始化列表
arr: list[int] = [1, 3, 2, 5, 4]
arr = [1, 3, 2, 5, 4]
print("列表 arr =", arr)
# 访问元素
@ -39,17 +39,17 @@ if __name__ == "__main__":
print("删除索引 3 处的元素,得到 arr =", arr)
# 通过索引遍历列表
count: int = 0
count = 0
for i in range(len(arr)):
count += 1
# 直接遍历列表元素
count: int = 0
count = 0
for n in arr:
count += 1
# 拼接两个列表
arr1: list[int] = [6, 8, 7, 10, 9]
arr1 = [6, 8, 7, 10, 9]
arr += arr1
print("将列表 arr1 拼接到 arr 之后,得到 arr =", arr)

View file

@ -35,7 +35,9 @@ def undo_choice(state: list[TreeNode], choice: TreeNode):
state.pop()
def backtrack(state: list[TreeNode], choices: list[TreeNode], res: list[list[TreeNode]]):
def backtrack(
state: list[TreeNode], choices: list[TreeNode], res: list[list[TreeNode]]
):
"""回溯算法:例题三"""
# 检查是否为解
if is_solution(state):
@ -59,7 +61,7 @@ if __name__ == "__main__":
root = list_to_tree([1, 7, 3, 4, 5, 6, 7])
print("\n初始化二叉树")
print_tree(root)
# 回溯算法
res = []
backtrack(state=[], choices=[root], res=res)

View file

@ -19,12 +19,12 @@ def function() -> int:
def constant(n: int) -> None:
"""常数阶"""
# 常量、变量、对象占用 O(1) 空间
a: int = 0
nums: list[int] = [0] * 10000
a = 0
nums = [0] * 10000
node = ListNode(0)
# 循环中的变量占用 O(1) 空间
for _ in range(n):
c: int = 0
c = 0
# 循环中的函数占用 O(1) 空间
for _ in range(n):
function()
@ -33,7 +33,7 @@ def constant(n: int) -> None:
def linear(n: int) -> None:
"""线性阶"""
# 长度为 n 的列表占用 O(n) 空间
nums: list[int] = [0] * n
nums = [0] * n
# 长度为 n 的哈希表占用 O(n) 空间
mapp = dict[int, str]()
for i in range(n):
@ -51,7 +51,7 @@ 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 = [[0] * n for _ in range(n)]
def quadratic_recur(n: int) -> int:
@ -59,7 +59,7 @@ def quadratic_recur(n: int) -> int:
if n <= 0:
return 0
# 数组 nums 长度为 n, n-1, ..., 2, 1
nums: list[int] = [0] * n
nums = [0] * n
return quadratic_recur(n - 1)

View file

@ -7,8 +7,8 @@ Author: Krahets (krahets@163.com)
def constant(n: int) -> int:
"""常数阶"""
count: int = 0
size: int = 100000
count = 0
size = 100000
for _ in range(size):
count += 1
return count
@ -16,7 +16,7 @@ def constant(n: int) -> int:
def linear(n: int) -> int:
"""线性阶"""
count: int = 0
count = 0
for _ in range(n):
count += 1
return count
@ -24,7 +24,7 @@ def linear(n: int) -> int:
def array_traversal(nums: list[int]) -> int:
"""线性阶(遍历数组)"""
count: int = 0
count = 0
# 循环次数与数组长度成正比
for num in nums:
count += 1
@ -33,7 +33,7 @@ def array_traversal(nums: list[int]) -> int:
def quadratic(n: int) -> int:
"""平方阶"""
count: int = 0
count = 0
# 循环次数与数组长度成平方关系
for i in range(n):
for j in range(n):
@ -43,7 +43,7 @@ def quadratic(n: int) -> int:
def bubble_sort(nums: list[int]) -> int:
"""平方阶(冒泡排序)"""
count: int = 0 # 计数器
count = 0 # 计数器
# 外循环:待排序元素数量为 n-1, n-2, ..., 1
for i in range(len(nums) - 1, 0, -1):
# 内循环:冒泡操作
@ -59,8 +59,8 @@ def bubble_sort(nums: list[int]) -> int:
def exponential(n: int) -> int:
"""指数阶(循环实现)"""
count: int = 0
base: int = 1
count = 0
base = 1
# cell 每轮一分为二,形成数列 1, 2, 4, 8, ..., 2^(n-1)
for _ in range(n):
for _ in range(base):
@ -79,7 +79,7 @@ def exp_recur(n: int) -> int:
def logarithmic(n: float) -> int:
"""对数阶(循环实现)"""
count: int = 0
count = 0
while n > 1:
n = n / 2
count += 1
@ -107,7 +107,7 @@ def factorial_recur(n: int) -> int:
"""阶乘阶(递归实现)"""
if n == 0:
return 1
count: int = 0
count = 0
# 从 1 个分裂出 n 个
for _ in range(n):
count += factorial_recur(n - 1)
@ -130,7 +130,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 = [i for i in range(n, 0, -1)] # [n, n-1, ..., 2, 1]
count: int = bubble_sort(nums)
print("平方阶(冒泡排序)的计算操作数量 =", count)

View file

@ -10,7 +10,7 @@ import random
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 = [i for i in range(1, n + 1)]
# 随机打乱数组元素
random.shuffle(nums)
return nums
@ -29,7 +29,7 @@ def find_one(nums: list[int]) -> int:
"""Driver Code"""
if __name__ == "__main__":
for i in range(10):
n: int = 100
n = 100
nums: list[int] = random_numbers(n)
index: int = find_one(nums)
print("\n数组 [ 1, 2, ..., n ] 被打乱后 =", nums)

View file

@ -88,8 +88,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 = [1, 3, 2, 5, 4]
edges = [[0, 1], [0, 3], [1, 2], [2, 3], [2, 4], [3, 4]]
graph = GraphAdjMat(vertices, edges)
print("\n初始化后,图为")
graph.print()

View file

@ -23,7 +23,7 @@ class ArrayHashMap:
def hash_func(self, key: int) -> int:
"""哈希函数"""
index: int = key % 100
index = key % 100
return index
def get(self, key: int) -> str:
@ -56,7 +56,7 @@ class ArrayHashMap:
def key_set(self) -> list[int]:
"""获取所有键"""
result: list[int] = []
result = []
for pair in self.buckets:
if pair is not None:
result.append(pair.key)
@ -64,7 +64,7 @@ class ArrayHashMap:
def value_set(self) -> list[str]:
"""获取所有值"""
result: list[str] = []
result = []
for pair in self.buckets:
if pair is not None:
result.append(pair.val)

View file

@ -64,7 +64,7 @@ if __name__ == "__main__":
# 输入列表并建堆
# 时间复杂度为 O(n) ,而非 O(nlogn)
min_heap: list[int] = [1, 3, 2, 5, 4]
min_heap = [1, 3, 2, 5, 4]
heapq.heapify(min_heap)
print("\n输入列表并建立小顶堆后")
print_heap(min_heap)

View file

@ -40,8 +40,8 @@ def binary_search_lcro(nums: list[int], target: int) -> int:
"""Driver Code"""
if __name__ == "__main__":
target: int = 6
nums: list[int] = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35]
target = 6
nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35]
# 二分查找(双闭区间)
index: int = binary_search(nums, target)

View file

@ -41,8 +41,8 @@ def binary_search_right_edge(nums: list[int], target: int) -> int:
"""Driver Code"""
if __name__ == "__main__":
target: int = 6
nums: list[int] = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15]
target = 6
nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15]
# 二分查找最左一个元素
index_left = binary_search_left_edge(nums, target)

View file

@ -28,10 +28,10 @@ def hashing_search_linkedlist(
"""Driver Code"""
if __name__ == "__main__":
target: int = 3
target = 3
# 哈希查找(数组)
nums: list[int] = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8]
nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8]
# 初始化哈希表
map0 = dict[int, int]()
for i in range(len(nums)):

View file

@ -31,10 +31,10 @@ def linear_search_linkedlist(head: ListNode, target: int) -> ListNode | None:
"""Driver Code"""
if __name__ == "__main__":
target: int = 3
target = 3
# 在数组中执行线性查找
nums: list[int] = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8]
nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8]
index: int = linear_search_array(nums, target)
print("目标元素 3 的索引 =", index)

View file

@ -7,7 +7,7 @@ Author: timi (xisunyy@163.com)
def bubble_sort(nums: list[int]) -> None:
"""冒泡排序"""
n: int = len(nums)
n = len(nums)
# 外循环:待排序元素数量为 n-1, n-2, ..., 1
for i in range(n - 1, 0, -1):
# 内循环:冒泡操作
@ -19,10 +19,10 @@ def bubble_sort(nums: list[int]) -> None:
def bubble_sort_with_flag(nums: list[int]) -> None:
"""冒泡排序(标志优化)"""
n: int = len(nums)
n = len(nums)
# 外循环:待排序元素数量为 n-1, n-2, ..., 1
for i in range(n - 1, 0, -1):
flag: bool = False # 初始化标志位
flag = False # 初始化标志位
# 内循环:冒泡操作
for j in range(i):
if nums[j] > nums[j + 1]:
@ -35,10 +35,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 = [4, 1, 3, 1, 5, 2]
bubble_sort(nums)
print("排序后数组 nums =", nums)
nums1: list[int] = [4, 1, 3, 1, 5, 2]
nums1 = [4, 1, 3, 1, 5, 2]
bubble_sort_with_flag(nums1)
print("排序后数组 nums =", nums1)

View file

@ -9,8 +9,8 @@ def insertion_sort(nums: list[int]) -> None:
"""插入排序"""
# 外循环base = nums[1], nums[2], ..., nums[n-1]
for i in range(1, len(nums)):
base: int = nums[i]
j: int = i - 1
base = nums[i]
j = i - 1
# 内循环:将 base 插入到左边的正确位置
while j >= 0 and nums[j] > base:
nums[j + 1] = nums[j] # 1. 将 nums[j] 向右移动一位
@ -20,6 +20,6 @@ def insertion_sort(nums: list[int]) -> None:
"""Driver Code"""
if __name__ == "__main__":
nums: list[int] = [4, 1, 3, 1, 5, 2]
nums = [4, 1, 3, 1, 5, 2]
insertion_sort(nums)
print("排序后数组 nums =", nums)

View file

@ -10,16 +10,16 @@ def merge(nums: list[int], left: int, mid: int, right: int) -> None:
# 左子数组区间 [left, mid]
# 右子数组区间 [mid + 1, right]
# 初始化辅助数组
tmp: list[int] = list(nums[left : right + 1])
tmp = list(nums[left : right + 1])
# 左子数组的起始索引和结束索引
left_start: int = 0
left_end: int = mid - left
left_start = 0
left_end = mid - left
# 右子数组的起始索引和结束索引
right_start: int = mid + 1 - left
right_end: int = right - left
right_start = mid + 1 - left
right_end = right - left
# i, j 分别指向左子数组、右子数组的首元素
i: int = left_start
j: int = right_start
i = left_start
j = right_start
# 通过覆盖原数组 nums 来合并左子数组和右子数组
for k in range(left, right + 1):
# 若“左子数组已全部合并完”,则选取右子数组元素,并且 j++
@ -42,7 +42,7 @@ def merge_sort(nums: list[int], left: int, right: int) -> None:
if left >= right:
return # 当子数组长度为 1 时终止递归
# 划分阶段
mid: int = (left + right) // 2 # 计算中点
mid = (left + right) // 2 # 计算中点
merge_sort(nums, left, mid) # 递归左子数组
merge_sort(nums, mid + 1, right) # 递归右子数组
# 合并阶段
@ -51,6 +51,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 = [7, 3, 2, 6, 0, 1, 5, 4]
merge_sort(nums, 0, len(nums) - 1)
print("归并排序完成后 nums =", nums)

View file

@ -29,7 +29,7 @@ class QuickSort:
if left >= right:
return
# 哨兵划分
pivot: int = self.partition(nums, left, right)
pivot = self.partition(nums, left, right)
# 递归左子数组、右子数组
self.quick_sort(nums, left, pivot - 1)
self.quick_sort(nums, pivot + 1, right)
@ -51,7 +51,7 @@ class QuickSortMedian:
def partition(self, nums: list[int], left: int, right: int) -> int:
"""哨兵划分(三数取中值)"""
# 以 nums[left] 作为基准数
med: int = self.median_three(nums, left, (left + right) // 2, right)
med = self.median_three(nums, left, (left + right) // 2, right)
# 将中位数交换至数组最左端
nums[left], nums[med] = nums[med], nums[left]
# 以 nums[left] 作为基准数
@ -73,7 +73,7 @@ class QuickSortMedian:
if left >= right:
return
# 哨兵划分
pivot: int = self.partition(nums, left, right)
pivot = self.partition(nums, left, right)
# 递归左子数组、右子数组
self.quick_sort(nums, left, pivot - 1)
self.quick_sort(nums, pivot + 1, right)
@ -102,7 +102,7 @@ class QuickSortTailCall:
# 子数组长度为 1 时终止
while left < right:
# 哨兵划分操作
pivot: int = self.partition(nums, left, right)
pivot = self.partition(nums, left, right)
# 对两个子数组中较短的那个执行快排
if pivot - left < right - pivot:
self.quick_sort(nums, left, pivot - 1) # 递归排序左子数组
@ -115,16 +115,16 @@ class QuickSortTailCall:
"""Driver Code"""
if __name__ == "__main__":
# 快速排序
nums: list[int] = [2, 4, 1, 0, 3, 5]
nums = [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 = [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= [2, 4, 1, 0, 3, 5]
QuickSortTailCall().quick_sort(nums2, 0, len(nums2) - 1)
print("快速排序(尾递归优化)完成后 nums =", nums2)

View file

@ -53,7 +53,7 @@ class ArrayQueue:
def to_list(self) -> list[int]:
"""返回列表用于打印"""
res: list[int] = [0] * self.size()
res = [0] * self.size()
j: int = self.__front
for i in range(self.size()):
res[i] = self.__nums[(j % self.capacity())]

View file

@ -104,8 +104,8 @@ class LinkedListDeque:
def to_array(self) -> list[int]:
"""返回数组用于打印"""
node: ListNode | None = self.front
res: list[int] = [0] * self.size()
node = self.front
res = [0] * self.size()
for i in range(self.size()):
res[i] = node.val
node = node.next

View file

@ -49,7 +49,7 @@ class LinkedListStack:
def to_list(self) -> list[int]:
"""转化为列表用于打印"""
arr: list[int] = []
arr = []
node = self.__peek
while node:
arr.append(node.val)

View file

@ -26,7 +26,7 @@ class BinarySearchTree:
return None
# 将数组中间节点作为根节点
mid: int = (start_index + end_index) // 2
mid = (start_index + end_index) // 2
root = TreeNode(nums[mid])
# 递归建立左子树和右子树
root.left = self.build_tree(

View file

@ -17,7 +17,7 @@ def level_order(root: TreeNode | None) -> list[int]:
queue: deque[TreeNode] = deque()
queue.append(root)
# 初始化一个列表,用于保存遍历序列
res: list[int] = []
res = []
while queue:
node: TreeNode = queue.popleft() # 队列出队
res.append(node.val) # 保存节点值

View file

@ -22,7 +22,7 @@ def list_to_tree(arr: list[int]) -> TreeNode | None:
if not arr:
return None
i: int = 0
i = 0
root = TreeNode(arr[0])
queue: deque[TreeNode] = deque([root])
while queue:

View file

@ -10,10 +10,9 @@ from .linked_list import ListNode, linked_list_to_list
def print_matrix(mat: list[list[int]]) -> None:
"""Print a matrix"""
s: list[str] = []
s = []
for arr in mat:
s.append(" " + str(arr))
print("[\n" + ",\n".join(s) + "\n]")
@ -47,7 +46,7 @@ def print_tree(
if root is None:
return
prev_str: str = " "
prev_str = " "
trunk = Trunk(prev, prev_str)
print_tree(root.right, trunk, True)

View file

@ -430,12 +430,12 @@
```python title="list.py"
# 通过索引遍历列表
count: int = 0
count = 0
for i in range(len(list)):
count += 1
# 直接遍历列表元素
count: int = 0
count = 0
for n in list:
count += 1
```

View file

@ -87,10 +87,10 @@
return 0
def algorithm(n) -> int: # 输入数据
A: int = 0 # 暂存数据(常量,一般用大写字母表示)
b: int = 0 # 暂存数据(变量)
A = 0 # 暂存数据(常量,一般用大写字母表示)
b = 0 # 暂存数据(变量)
node = Node(0) # 暂存数据(对象)
c: int = function() # 栈帧空间(调用函数)
c = function() # 栈帧空间(调用函数)
return A + b + c # 输出数据
```
@ -293,10 +293,10 @@
```python title=""
def algorithm(n: int) -> None:
a: int = 0 # O(1)
b: List[int] = [0] * 10000 # O(1)
a = 0 # O(1)
b = [0] * 10000 # O(1)
if n > 10:
nums: List[int] = [0] * n # O(n)
nums = [0] * n # O(n)
```
=== "Go"

View file

@ -415,7 +415,7 @@ $$
```python title=""
def algorithm(n: int) -> None:
a: int = 1 # +1
a = 1 # +1
a = a + 1 # +1
a = a * 2 # +1
# 循环 n 次
@ -604,8 +604,8 @@ $$
```python title=""
def algorithm(n: int) -> None:
a: int = 1 # +0技巧 1
a = a + n # +0技巧 1
a = 1 # +0技巧 1
a = a + n # +0技巧 1
# +n技巧 2
for i in range(5 * n + 1):
print(0)
@ -619,7 +619,7 @@ $$
```go title=""
func algorithm(n int) {
a := 1 // +0技巧 1
a := 1 // +0技巧 1
a = a + n // +0技巧 1
// +n技巧 2
for i := 0; i < 5 * n + 1; i++ {