Fix Python code.

pull/860/head
krahets 1 year ago
parent a8c624fa5a
commit 2976d9ff56

@ -10,77 +10,77 @@ class MyList:
def __init__(self):
"""构造方法"""
self.__capacity: int = 10 # 列表容量
self.__arr: list[int] = [0] * self.__capacity # 数组(存储列表元素)
self.__size: int = 0 # 列表长度(即当前元素数量)
self.__extend_ratio: int = 2 # 每次列表扩容的倍数
self._capacity: int = 10 # 列表容量
self._arr: list[int] = [0] * self._capacity # 数组(存储列表元素)
self._size: int = 0 # 列表长度(即当前元素数量)
self._extend_ratio: int = 2 # 每次列表扩容的倍数
def size(self) -> int:
"""获取列表长度(即当前元素数量)"""
return self.__size
return self._size
def capacity(self) -> int:
"""获取列表容量"""
return self.__capacity
return self._capacity
def get(self, index: int) -> int:
"""访问元素"""
# 索引如果越界则抛出异常,下同
if index < 0 or index >= self.__size:
if index < 0 or index >= self._size:
raise IndexError("索引越界")
return self.__arr[index]
return self._arr[index]
def set(self, num: int, index: int):
"""更新元素"""
if index < 0 or index >= self.__size:
if index < 0 or index >= self._size:
raise IndexError("索引越界")
self.__arr[index] = num
self._arr[index] = num
def add(self, num: int):
"""尾部添加元素"""
# 元素数量超出容量时,触发扩容机制
if self.size() == self.capacity():
self.extend_capacity()
self.__arr[self.__size] = num
self.__size += 1
self._arr[self._size] = num
self._size += 1
def insert(self, num: int, index: int):
"""中间插入元素"""
if index < 0 or index >= self.__size:
if index < 0 or index >= self._size:
raise IndexError("索引越界")
# 元素数量超出容量时,触发扩容机制
if self.__size == self.capacity():
if self._size == self.capacity():
self.extend_capacity()
# 将索引 index 以及之后的元素都向后移动一位
for j in range(self.__size - 1, index - 1, -1):
self.__arr[j + 1] = self.__arr[j]
self.__arr[index] = num
for j in range(self._size - 1, index - 1, -1):
self._arr[j + 1] = self._arr[j]
self._arr[index] = num
# 更新元素数量
self.__size += 1
self._size += 1
def remove(self, index: int) -> int:
"""删除元素"""
if index < 0 or index >= self.__size:
if index < 0 or index >= self._size:
raise IndexError("索引越界")
num = self.__arr[index]
num = self._arr[index]
# 索引 i 之后的元素都向前移动一位
for j in range(index, self.__size - 1):
self.__arr[j] = self.__arr[j + 1]
for j in range(index, self._size - 1):
self._arr[j] = self._arr[j + 1]
# 更新元素数量
self.__size -= 1
self._size -= 1
# 返回被删除元素
return num
def extend_capacity(self):
"""列表扩容"""
# 新建一个长度为原数组 __extend_ratio 倍的新数组,并将原数组拷贝到新数组
self.__arr = self.__arr + [0] * self.capacity() * (self.__extend_ratio - 1)
self._arr = self._arr + [0] * self.capacity() * (self._extend_ratio - 1)
# 更新列表容量
self.__capacity = len(self.__arr)
self._capacity = len(self._arr)
def to_array(self) -> list[int]:
"""返回有效长度的列表"""
return self.__arr[: self.__size]
return self._arr[: self._size]
"""Driver Code"""

@ -10,21 +10,21 @@ class ArrayDeque:
def __init__(self, capacity: int):
"""构造方法"""
self.__nums: list[int] = [0] * capacity
self.__front: int = 0
self.__size: int = 0
self._nums: list[int] = [0] * capacity
self._front: int = 0
self._size: int = 0
def capacity(self) -> int:
"""获取双向队列的容量"""
return len(self.__nums)
return len(self._nums)
def size(self) -> int:
"""获取双向队列的长度"""
return self.__size
return self._size
def is_empty(self) -> bool:
"""判断双向队列是否为空"""
return self.__size == 0
return self._size == 0
def index(self, i: int) -> int:
"""计算环形数组索引"""
@ -35,61 +35,61 @@ class ArrayDeque:
def push_first(self, num: int):
"""队首入队"""
if self.__size == self.capacity():
if self._size == self.capacity():
print("双向队列已满")
return
# 队首指针向左移动一位
# 通过取余操作,实现 front 越过数组头部后回到尾部
self.__front = self.index(self.__front - 1)
self._front = self.index(self._front - 1)
# 将 num 添加至队首
self.__nums[self.__front] = num
self.__size += 1
self._nums[self._front] = num
self._size += 1
def push_last(self, num: int):
"""队尾入队"""
if self.__size == self.capacity():
if self._size == self.capacity():
print("双向队列已满")
return
# 计算尾指针,指向队尾索引 + 1
rear = self.index(self.__front + self.__size)
rear = self.index(self._front + self._size)
# 将 num 添加至队尾
self.__nums[rear] = num
self.__size += 1
self._nums[rear] = num
self._size += 1
def pop_first(self) -> int:
"""队首出队"""
num = self.peek_first()
# 队首指针向后移动一位
self.__front = self.index(self.__front + 1)
self.__size -= 1
self._front = self.index(self._front + 1)
self._size -= 1
return num
def pop_last(self) -> int:
"""队尾出队"""
num = self.peek_last()
self.__size -= 1
self._size -= 1
return num
def peek_first(self) -> int:
"""访问队首元素"""
if self.is_empty():
raise IndexError("双向队列为空")
return self.__nums[self.__front]
return self._nums[self._front]
def peek_last(self) -> int:
"""访问队尾元素"""
if self.is_empty():
raise IndexError("双向队列为空")
# 计算尾元素索引
last = self.index(self.__front + self.__size - 1)
return self.__nums[last]
last = self.index(self._front + self._size - 1)
return self._nums[last]
def to_array(self) -> list[int]:
"""返回数组用于打印"""
# 仅转换有效长度范围内的列表元素
res = []
for i in range(self.__size):
res.append(self.__nums[self.index(self.__front + i)])
for i in range(self._size):
res.append(self._nums[self.index(self._front + i)])
return res

@ -10,53 +10,53 @@ class ArrayQueue:
def __init__(self, size: int):
"""构造方法"""
self.__nums: list[int] = [0] * size # 用于存储队列元素的数组
self.__front: int = 0 # 队首指针,指向队首元素
self.__size: int = 0 # 队列长度
self._nums: list[int] = [0] * size # 用于存储队列元素的数组
self._front: int = 0 # 队首指针,指向队首元素
self._size: int = 0 # 队列长度
def capacity(self) -> int:
"""获取队列的容量"""
return len(self.__nums)
return len(self._nums)
def size(self) -> int:
"""获取队列的长度"""
return self.__size
return self._size
def is_empty(self) -> bool:
"""判断队列是否为空"""
return self.__size == 0
return self._size == 0
def push(self, num: int):
"""入队"""
if self.__size == self.capacity():
if self._size == self.capacity():
raise IndexError("队列已满")
# 计算尾指针,指向队尾索引 + 1
# 通过取余操作,实现 rear 越过数组尾部后回到头部
rear: int = (self.__front + self.__size) % self.capacity()
rear: int = (self._front + self._size) % self.capacity()
# 将 num 添加至队尾
self.__nums[rear] = num
self.__size += 1
self._nums[rear] = num
self._size += 1
def pop(self) -> int:
"""出队"""
num: int = self.peek()
# 队首指针向后移动一位,若越过尾部则返回到数组头部
self.__front = (self.__front + 1) % self.capacity()
self.__size -= 1
self._front = (self._front + 1) % self.capacity()
self._size -= 1
return num
def peek(self) -> int:
"""访问队首元素"""
if self.is_empty():
raise IndexError("队列为空")
return self.__nums[self.__front]
return self._nums[self._front]
def to_list(self) -> list[int]:
"""返回列表用于打印"""
res = [0] * self.size()
j: int = self.__front
j: int = self._front
for i in range(self.size()):
res[i] = self.__nums[(j % self.capacity())]
res[i] = self._nums[(j % self.capacity())]
j += 1
return res

@ -10,35 +10,35 @@ class ArrayStack:
def __init__(self):
"""构造方法"""
self.__stack: list[int] = []
self._stack: list[int] = []
def size(self) -> int:
"""获取栈的长度"""
return len(self.__stack)
return len(self._stack)
def is_empty(self) -> bool:
"""判断栈是否为空"""
return self.__stack == []
return self._stack == []
def push(self, item: int):
"""入栈"""
self.__stack.append(item)
self._stack.append(item)
def pop(self) -> int:
"""出栈"""
if self.is_empty():
raise IndexError("栈为空")
return self.__stack.pop()
return self._stack.pop()
def peek(self) -> int:
"""访问栈顶元素"""
if self.is_empty():
raise IndexError("栈为空")
return self.__stack[-1]
return self._stack[-1]
def to_list(self) -> list[int]:
"""返回列表用于打印"""
return self.__stack
return self._stack
"""Driver Code"""

@ -20,13 +20,13 @@ class LinkedListDeque:
def __init__(self):
"""构造方法"""
self.front: ListNode | None = None # 头节点 front
self.rear: ListNode | None = None # 尾节点 rear
self.__size: int = 0 # 双向队列的长度
self._front: ListNode | None = None # 头节点 front
self._rear: ListNode | None = None # 尾节点 rear
self._size: int = 0 # 双向队列的长度
def size(self) -> int:
"""获取双向队列的长度"""
return self.__size
return self._size
def is_empty(self) -> bool:
"""判断双向队列是否为空"""
@ -37,20 +37,20 @@ class LinkedListDeque:
node = ListNode(num)
# 若链表为空,则令 front, rear 都指向 node
if self.is_empty():
self.front = self.rear = node
self._front = self._rear = node
# 队首入队操作
elif is_front:
# 将 node 添加至链表头部
self.front.prev = node
node.next = self.front
self.front = node # 更新头节点
self._front.prev = node
node.next = self._front
self._front = node # 更新头节点
# 队尾入队操作
else:
# 将 node 添加至链表尾部
self.rear.next = node
node.prev = self.rear
self.rear = node # 更新尾节点
self.__size += 1 # 更新队列长度
self._rear.next = node
node.prev = self._rear
self._rear = node # 更新尾节点
self._size += 1 # 更新队列长度
def push_first(self, num: int):
"""队首入队"""
@ -66,23 +66,23 @@ class LinkedListDeque:
raise IndexError("双向队列为空")
# 队首出队操作
if is_front:
val: int = self.front.val # 暂存头节点值
val: int = self._front.val # 暂存头节点值
# 删除头节点
fnext: ListNode | None = self.front.next
fnext: ListNode | None = self._front.next
if fnext != None:
fnext.prev = None
self.front.next = None
self.front = fnext # 更新头节点
self._front.next = None
self._front = fnext # 更新头节点
# 队尾出队操作
else:
val: int = self.rear.val # 暂存尾节点值
val: int = self._rear.val # 暂存尾节点值
# 删除尾节点
rprev: ListNode | None = self.rear.prev
rprev: ListNode | None = self._rear.prev
if rprev != None:
rprev.next = None
self.rear.prev = None
self.rear = rprev # 更新尾节点
self.__size -= 1 # 更新队列长度
self._rear.prev = None
self._rear = rprev # 更新尾节点
self._size -= 1 # 更新队列长度
return val
def pop_first(self) -> int:
@ -97,17 +97,17 @@ class LinkedListDeque:
"""访问队首元素"""
if self.is_empty():
raise IndexError("双向队列为空")
return self.front.val
return self._front.val
def peek_last(self) -> int:
"""访问队尾元素"""
if self.is_empty():
raise IndexError("双向队列为空")
return self.rear.val
return self._rear.val
def to_array(self) -> list[int]:
"""返回数组用于打印"""
node = self.front
node = self._front
res = [0] * self.size()
for i in range(self.size()):
res[i] = node.val

@ -15,50 +15,50 @@ class LinkedListQueue:
def __init__(self):
"""构造方法"""
self.__front: ListNode | None = None # 头节点 front
self.__rear: ListNode | None = None # 尾节点 rear
self.__size: int = 0
self._front: ListNode | None = None # 头节点 front
self._rear: ListNode | None = None # 尾节点 rear
self._size: int = 0
def size(self) -> int:
"""获取队列的长度"""
return self.__size
return self._size
def is_empty(self) -> bool:
"""判断队列是否为空"""
return not self.__front
return not self._front
def push(self, num: int):
"""入队"""
# 尾节点后添加 num
node = ListNode(num)
# 如果队列为空,则令头、尾节点都指向该节点
if self.__front is None:
self.__front = node
self.__rear = node
if self._front is None:
self._front = node
self._rear = node
# 如果队列不为空,则将该节点添加到尾节点后
else:
self.__rear.next = node
self.__rear = node
self.__size += 1
self._rear.next = node
self._rear = node
self._size += 1
def pop(self) -> int:
"""出队"""
num = self.peek()
# 删除头节点
self.__front = self.__front.next
self.__size -= 1
self._front = self._front.next
self._size -= 1
return num
def peek(self) -> int:
"""访问队首元素"""
if self.is_empty():
raise IndexError("队列为空")
return self.__front.val
return self._front.val
def to_list(self) -> list[int]:
"""转化为列表用于打印"""
queue = []
temp = self.__front
temp = self._front
while temp:
queue.append(temp.val)
temp = temp.next

@ -15,41 +15,41 @@ class LinkedListStack:
def __init__(self):
"""构造方法"""
self.__peek: ListNode | None = None
self.__size: int = 0
self._peek: ListNode | None = None
self._size: int = 0
def size(self) -> int:
"""获取栈的长度"""
return self.__size
return self._size
def is_empty(self) -> bool:
"""判断栈是否为空"""
return not self.__peek
return not self._peek
def push(self, val: int):
"""入栈"""
node = ListNode(val)
node.next = self.__peek
self.__peek = node
self.__size += 1
node.next = self._peek
self._peek = node
self._size += 1
def pop(self) -> int:
"""出栈"""
num = self.peek()
self.__peek = self.__peek.next
self.__size -= 1
self._peek = self._peek.next
self._size -= 1
return num
def peek(self) -> int:
"""访问栈顶元素"""
if self.is_empty():
raise IndexError("栈为空")
return self.__peek.val
return self._peek.val
def to_list(self) -> list[int]:
"""转化为列表用于打印"""
arr = []
node = self.__peek
node = self._peek
while node:
arr.append(node.val)
node = node.next

@ -15,18 +15,18 @@ class ArrayBinaryTree:
def __init__(self, arr: list[int | None]):
"""构造方法"""
self.__tree = list(arr)
self._tree = list(arr)
def size(self):
"""节点数量"""
return len(self.__tree)
return len(self._tree)
def val(self, i: int) -> int:
"""获取索引为 i 节点的值"""
# 若索引越界,则返回 None ,代表空位
if i < 0 or i >= self.size():
return None
return self.__tree[i]
return self._tree[i]
def left(self, i: int) -> int | None:
"""获取索引为 i 节点的左子节点的索引"""
@ -49,18 +49,18 @@ class ArrayBinaryTree:
self.res.append(self.val(i))
return self.res
def __dfs(self, i: int, order: str):
def dfs(self, i: int, order: str):
"""深度优先遍历"""
if self.val(i) is None:
return
# 前序遍历
if order == "pre":
self.res.append(self.val(i))
self.__dfs(self.left(i), order)
self.dfs(self.left(i), order)
# 中序遍历
if order == "in":
self.res.append(self.val(i))
self.__dfs(self.right(i), order)
self.dfs(self.right(i), order)
# 后序遍历
if order == "post":
self.res.append(self.val(i))
@ -68,19 +68,19 @@ class ArrayBinaryTree:
def pre_order(self) -> list[int]:
"""前序遍历"""
self.res = []
self.__dfs(0, order="pre")
self.dfs(0, order="pre")
return self.res
def in_order(self) -> list[int]:
"""中序遍历"""
self.res = []
self.__dfs(0, order="in")
self.dfs(0, order="in")
return self.res
def post_order(self) -> list[int]:
"""后序遍历"""
self.res = []
self.__dfs(0, order="post")
self.dfs(0, order="post")
return self.res

@ -15,7 +15,11 @@ class AVLTree:
def __init__(self, root: TreeNode | None = None):
"""构造方法"""
self.root = root
self._root = None
def get_root(self) -> TreeNode | None:
"""获取二叉树根节点"""
return self._root
def height(self, node: TreeNode | None) -> int:
"""获取节点高度"""
@ -24,7 +28,7 @@ class AVLTree:
return node.height
return -1
def __update_height(self, node: TreeNode | None):
def update_height(self, node: TreeNode | None):
"""更新节点高度"""
# 节点高度等于最高子树高度 + 1
node.height = max([self.height(node.left), self.height(node.right)]) + 1
@ -37,7 +41,7 @@ class AVLTree:
# 节点平衡因子 = 左子树高度 - 右子树高度
return self.height(node.left) - self.height(node.right)
def __right_rotate(self, node: TreeNode | None) -> TreeNode | None:
def right_rotate(self, node: TreeNode | None) -> TreeNode | None:
"""右旋操作"""
child = node.left
grand_child = child.right
@ -45,12 +49,12 @@ class AVLTree:
child.right = node
node.left = grand_child
# 更新节点高度
self.__update_height(node)
self.__update_height(child)
self.update_height(node)
self.update_height(child)
# 返回旋转后子树的根节点
return child
def __left_rotate(self, node: TreeNode | None) -> TreeNode | None:
def left_rotate(self, node: TreeNode | None) -> TreeNode | None:
"""左旋操作"""
child = node.right
grand_child = child.left
@ -58,12 +62,12 @@ class AVLTree:
child.left = node
node.right = grand_child
# 更新节点高度
self.__update_height(node)
self.__update_height(child)
self.update_height(node)
self.update_height(child)
# 返回旋转后子树的根节点
return child
def __rotate(self, node: TreeNode | None) -> TreeNode | None:
def rotate(self, node: TreeNode | None) -> TreeNode | None:
"""执行旋转操作,使该子树重新恢复平衡"""
# 获取节点 node 的平衡因子
balance_factor = self.balance_factor(node)
@ -71,57 +75,57 @@ class AVLTree:
if balance_factor > 1:
if self.balance_factor(node.left) >= 0:
# 右旋
return self.__right_rotate(node)
return self.right_rotate(node)
else:
# 先左旋后右旋
node.left = self.__left_rotate(node.left)
return self.__right_rotate(node)
node.left = self.left_rotate(node.left)
return self.right_rotate(node)
# 右偏树
elif balance_factor < -1:
if self.balance_factor(node.right) <= 0:
# 左旋
return self.__left_rotate(node)
return self.left_rotate(node)
else:
# 先右旋后左旋
node.right = self.__right_rotate(node.right)
return self.__left_rotate(node)
node.right = self.right_rotate(node.right)
return self.left_rotate(node)
# 平衡树,无须旋转,直接返回
return node
def insert(self, val):
"""插入节点"""
self.root = self.__insert_helper(self.root, val)
self._root = self.insert_helper(self._root, val)
def __insert_helper(self, node: TreeNode | None, val: int) -> TreeNode:
def insert_helper(self, node: TreeNode | None, val: int) -> TreeNode:
"""递归插入节点(辅助方法)"""
if node is None:
return TreeNode(val)
# 1. 查找插入位置,并插入节点
if val < node.val:
node.left = self.__insert_helper(node.left, val)
node.left = self.insert_helper(node.left, val)
elif val > node.val:
node.right = self.__insert_helper(node.right, val)
node.right = self.insert_helper(node.right, val)
else:
# 重复节点不插入,直接返回
return node
# 更新节点高度
self.__update_height(node)
self.update_height(node)
# 2. 执行旋转操作,使该子树重新恢复平衡
return self.__rotate(node)
return self.rotate(node)
def remove(self, val: int):
"""删除节点"""
self.root = self.__remove_helper(self.root, val)
self._root = self.remove_helper(self._root, val)
def __remove_helper(self, node: TreeNode | None, val: int) -> TreeNode | None:
def remove_helper(self, node: TreeNode | None, val: int) -> TreeNode | None:
"""递归删除节点(辅助方法)"""
if node is None:
return None
# 1. 查找节点,并删除之
if val < node.val:
node.left = self.__remove_helper(node.left, val)
node.left = self.remove_helper(node.left, val)
elif val > node.val:
node.right = self.__remove_helper(node.right, val)
node.right = self.remove_helper(node.right, val)
else:
if node.left is None or node.right is None:
child = node.left or node.right
@ -136,16 +140,16 @@ class AVLTree:
temp = node.right
while temp.left is not None:
temp = temp.left
node.right = self.__remove_helper(node.right, temp.val)
node.right = self.remove_helper(node.right, temp.val)
node.val = temp.val
# 更新节点高度
self.__update_height(node)
self.update_height(node)
# 2. 执行旋转操作,使该子树重新恢复平衡
return self.__rotate(node)
return self.rotate(node)
def search(self, val: int) -> TreeNode | None:
"""查找节点"""
cur = self.root
cur = self._root
# 循环查找,越过叶节点后跳出
while cur is not None:
# 目标节点在 cur 的右子树中
@ -167,12 +171,12 @@ if __name__ == "__main__":
def test_insert(tree: AVLTree, val: int):
tree.insert(val)
print("\n插入节点 {}AVL 树为".format(val))
print_tree(tree.root)
print_tree(tree.get_root())
def test_remove(tree: AVLTree, val: int):
tree.remove(val)
print("\n删除节点 {}AVL 树为".format(val))
print_tree(tree.root)
print_tree(tree.get_root())
# 初始化空 AVL 树
avl_tree = AVLTree()

@ -16,15 +16,15 @@ class BinarySearchTree:
def __init__(self):
"""构造方法"""
# 初始化空树
self.__root = None
self._root = None
def get_root(self) -> TreeNode | None:
"""获取二叉树根节点"""
return self.__root
return self._root
def search(self, num: int) -> TreeNode | None:
"""查找节点"""
cur = self.__root
cur = self._root
# 循环查找,越过叶节点后跳出
while cur is not None:
# 目标节点在 cur 的右子树中
@ -41,11 +41,11 @@ class BinarySearchTree:
def insert(self, num: int):
"""插入节点"""
# 若树为空,则初始化根节点
if self.__root is None:
self.__root = TreeNode(num)
if self._root is None:
self._root = TreeNode(num)
return
# 循环查找,越过叶节点后跳出
cur, pre = self.__root, None
cur, pre = self._root, None
while cur is not None:
# 找到重复节点,直接返回
if cur.val == num:
@ -67,10 +67,10 @@ class BinarySearchTree:
def remove(self, num: int):
"""删除节点"""
# 若树为空,直接提前返回
if self.__root is None:
if self._root is None:
return
# 循环查找,越过叶节点后跳出
cur, pre = self.__root, None
cur, pre = self._root, None
while cur is not None:
# 找到待删除节点,跳出循环
if cur.val == num:
@ -91,14 +91,14 @@ class BinarySearchTree:
# 当子节点数量 = 0 / 1 时, child = null / 该子节点
child = cur.left or cur.right
# 删除节点 cur
if cur != self.__root:
if cur != self._root:
if pre.left == cur:
pre.left = child
else:
pre.right = child
else:
# 若删除节点为根节点,则重新指定根节点
self.__root = child
self._root = child
# 子节点数量 = 2
else:
# 获取中序遍历中 cur 的下一个节点

Loading…
Cancel
Save