Add typing annotations to Python codes. (#411)

This commit is contained in:
Yudong Jin
2023-03-12 18:49:52 +08:00
committed by GitHub
parent 2029d2b939
commit 9151eaf533
50 changed files with 577 additions and 817 deletions

View File

@ -5,7 +5,7 @@ import queue
import random
import functools
import collections
from typing import Optional, List, Dict, DefaultDict, OrderedDict, Set, Deque
from typing import Optional, Tuple, List, Dict, DefaultDict, OrderedDict, Set, Deque
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 .vertex import Vertex, vals_to_vets, vets_to_vals

View File

@ -5,36 +5,26 @@ Author: Krahets (krahets@163.com)
"""
import collections
from typing import List, Deque, Optional
class TreeNode:
"""Definition for a binary tree node
"""
def __init__(self, val=0, left=None, right=None):
self.val = val # 结点
self.height = 0 # 结点高度
self.left = left # 子结点引用
self.right = right # 右子结点引用
""" 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 __str__(self):
val = self.val
left_node_val = self.left.val if self.left else None
right_node_val = self.right.val if self.right else None
return "<TreeNode: {}, leftTreeNode: {}, rightTreeNode: {}>".format(val, left_node_val, right_node_val)
__repr__ = __str__
def list_to_tree(arr):
"""Generate a binary tree with a list
"""
def list_to_tree(arr: List[int]) -> Optional[TreeNode]:
""" Generate a binary tree with a list """
if not arr:
return None
i = 0
i: int = 0
root = TreeNode(arr[0])
queue = collections.deque([root])
queue: Deque[TreeNode] = collections.deque([root])
while queue:
node = queue.popleft()
node: TreeNode = queue.popleft()
i += 1
if i >= len(arr): break
if arr[i] != None:
@ -48,15 +38,14 @@ def list_to_tree(arr):
return root
def tree_to_list(root):
"""Serialize a tree into an array
"""
def tree_to_list(root: Optional[TreeNode]) -> List[int]:
""" Serialize a tree into an array """
if not root: return []
queue = collections.deque()
queue: Deque[TreeNode] = collections.deque()
queue.append(root)
res = []
res: List[int] = []
while queue:
node = queue.popleft()
node: Optional[TreeNode] = queue.popleft()
if node:
res.append(node.val)
queue.append(node.left)
@ -64,13 +53,12 @@ def tree_to_list(root):
else: res.append(None)
return res
def get_tree_node(root, val):
"""Get a tree node with specific value in a binary tree
"""
def get_tree_node(root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
""" Get a tree node with specific value in a binary tree """
if not root:
return
if root.val == val:
return root
left = get_tree_node(root.left, val)
right = get_tree_node(root.right, val)
left: Optional[TreeNode] = get_tree_node(root.left, val)
right: Optional[TreeNode] = get_tree_node(root.right, val)
return left if left else right

View File

@ -4,22 +4,16 @@ 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=0, next=None):
self.val = val
self.next = next
""" Definition for a singly-linked list node """
def __init__(self, val: int):
self.val: int = val # 结点值
self.next: Optional[ListNode] = None # 后继结点引用
def list_to_linked_list(arr):
"""Generate a linked list with a list
Args:
arr ([type]): [description]
Returns:
[type]: [description]
"""
def list_to_linked_list(arr: List[int]) -> Optional[ListNode]:
""" Generate a linked list with a list """
dum = head = ListNode(0)
for a in arr:
node = ListNode(a)
@ -27,31 +21,16 @@ def list_to_linked_list(arr):
head = head.next
return dum.next
def linked_list_to_list(head):
"""Serialize a linked list into an array
Args:
head ([type]): [description]
Returns:
[type]: [description]
"""
arr = []
def linked_list_to_list(head: Optional[ListNode]) -> List[int]:
""" Serialize a linked list into an array """
arr: List[int] = []
while head:
arr.append(head.val)
head = head.next
return arr
def get_list_node(head, val):
"""Get a list node with specific value from a linked list
Args:
head ([type]): [description]
val ([type]): [description]
Returns:
[type]: [description]
"""
def get_list_node(head: Optional[ListNode], val: int) -> Optional[ListNode]:
""" Get a list node with specific value from a linked list """
while head and head.val != val:
head = head.next
return head

View File

@ -4,57 +4,48 @@ Created Time: 2021-12-11
Author: Krahets (krahets@163.com), msk397 (machangxinq@gmail.com)
"""
from .binary_tree import TreeNode, tree_to_list, list_to_tree
from .binary_tree import TreeNode, list_to_tree
from .linked_list import ListNode, linked_list_to_list
def print_matrix(mat):
"""Print a matrix
from typing import List, Optional, Dict
Args:
mat ([type]): [description]
"""
pstr = []
def print_matrix(mat: List[List[int]]) -> None:
""" Print a matrix """
s: List[str] = []
for arr in mat:
pstr.append(' ' + str(arr))
s.append(' ' + str(arr))
print('[\n' + ',\n'.join(pstr) + '\n]')
print('[\n' + ',\n'.join(s) + '\n]')
def print_linked_list(head):
"""Print a linked list
Args:
head ([type]): [description]
"""
arr = linked_list_to_list(head)
def print_linked_list(head: Optional[ListNode]) -> None:
""" Print a linked list """
arr: List[int] = linked_list_to_list(head)
print(' -> '.join([str(a) for a in arr]))
class Trunk:
def __init__(self, prev=None, str=None):
self.prev = prev
self.str = str
def show_trunks(p):
def __init__(self, prev: Optional['Trunk'] = None, string: Optional[str] = None) -> None:
self.prev: Optional[Trunk] = prev
self.str: Optional[str] = string
def show_trunks(p: Optional[Trunk]) -> None:
if p is None:
return
show_trunks(p.prev)
print(p.str, end='')
def print_tree(root, prev=None, is_left=False):
"""Print a binary tree
This tree printer is borrowed from TECHIE DELIGHT
https://www.techiedelight.com/c-program-print-binary-tree/
Args:
root ([type]): [description]
prev ([type], optional): [description]. Defaults to None.
is_left (bool, optional): [description]. Defaults to False.
def print_tree(root: Optional[TreeNode], prev: Optional[Trunk] = None, is_left: bool = False) -> None:
"""
Print a binary tree
This tree printer is borrowed from TECHIE DELIGHT
https://www.techiedelight.com/c-program-print-binary-tree/
"""
if root is None:
return
prev_str = ' '
prev_str: str = ' '
trunk = Trunk(prev, prev_str)
print_tree(root.right, trunk, True)
if prev is None:
trunk.str = '———'
elif is_left:
@ -63,7 +54,7 @@ def print_tree(root, prev=None, is_left=False):
else:
trunk.str = '\———'
prev.str = prev_str
show_trunks(trunk)
print(' ' + str(root.val))
if prev:
@ -71,17 +62,14 @@ def print_tree(root, prev=None, is_left=False):
trunk.str = ' |'
print_tree(root.left, trunk, False)
def print_dict(d):
"""Print a dict
Args:
d ([type]): [description]
"""
for key, value in d.items():
def print_dict(mapp: Dict) -> None:
""" Print a dict """
for key, value in mapp.items():
print(key, '->', value)
def print_heap(heap):
print("堆的数组表示:", heap);
print("堆的树状表示:");
root = list_to_tree(heap)
print_tree(root);
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)
print_tree(root)