mirror of
https://github.com/krahets/hello-algo.git
synced 2025-11-02 04:31:55 +08:00
Update code style for Python
This commit is contained in:
12
codes/python/modules/__init__.py
Normal file
12
codes/python/modules/__init__.py
Normal file
@ -0,0 +1,12 @@
|
||||
import copy
|
||||
import math
|
||||
import heapq
|
||||
import queue
|
||||
import random
|
||||
import functools
|
||||
import collections
|
||||
from typing import Optional, 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
|
||||
from .print_util import print_matrix, print_linked_list, print_tree, print_dict, print_heap
|
||||
76
codes/python/modules/binary_tree.py
Normal file
76
codes/python/modules/binary_tree.py
Normal file
@ -0,0 +1,76 @@
|
||||
"""
|
||||
File: binary_tree.py
|
||||
Created Time: 2021-12-11
|
||||
Author: Krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
import collections
|
||||
|
||||
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 # 右子结点引用
|
||||
|
||||
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
|
||||
"""
|
||||
if not arr:
|
||||
return None
|
||||
|
||||
i = 0
|
||||
root = TreeNode(arr[0])
|
||||
queue = collections.deque([root])
|
||||
while queue:
|
||||
node = queue.popleft()
|
||||
i += 1
|
||||
if i >= len(arr): break
|
||||
if arr[i] != None:
|
||||
node.left = TreeNode(arr[i])
|
||||
queue.append(node.left)
|
||||
i += 1
|
||||
if i >= len(arr): break
|
||||
if arr[i] != None:
|
||||
node.right = TreeNode(arr[i])
|
||||
queue.append(node.right)
|
||||
|
||||
return root
|
||||
|
||||
def tree_to_list(root):
|
||||
"""Serialize a tree into an array
|
||||
"""
|
||||
if not root: return []
|
||||
queue = collections.deque()
|
||||
queue.append(root)
|
||||
res = []
|
||||
while queue:
|
||||
node = queue.popleft()
|
||||
if node:
|
||||
res.append(node.val)
|
||||
queue.append(node.left)
|
||||
queue.append(node.right)
|
||||
else: res.append(None)
|
||||
return res
|
||||
|
||||
def get_tree_node(root, val):
|
||||
"""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)
|
||||
return left if left else right
|
||||
57
codes/python/modules/linked_list.py
Normal file
57
codes/python/modules/linked_list.py
Normal file
@ -0,0 +1,57 @@
|
||||
"""
|
||||
File: linked_list.py
|
||||
Created Time: 2021-12-11
|
||||
Author: Krahets (krahets@163.com)
|
||||
"""
|
||||
|
||||
class ListNode:
|
||||
"""Definition for a singly-linked list node
|
||||
"""
|
||||
def __init__(self, val=0, next=None):
|
||||
self.val = val
|
||||
self.next = next
|
||||
|
||||
def list_to_linked_list(arr):
|
||||
"""Generate a linked list with a list
|
||||
|
||||
Args:
|
||||
arr ([type]): [description]
|
||||
|
||||
Returns:
|
||||
[type]: [description]
|
||||
"""
|
||||
dum = head = ListNode(0)
|
||||
for a in arr:
|
||||
node = ListNode(a)
|
||||
head.next = node
|
||||
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 = []
|
||||
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]
|
||||
"""
|
||||
while head and head.val != val:
|
||||
head = head.next
|
||||
return head
|
||||
87
codes/python/modules/print_util.py
Normal file
87
codes/python/modules/print_util.py
Normal file
@ -0,0 +1,87 @@
|
||||
"""
|
||||
File: print_util.py
|
||||
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 .linked_list import ListNode, linked_list_to_list
|
||||
|
||||
def print_matrix(mat):
|
||||
"""Print a matrix
|
||||
|
||||
Args:
|
||||
mat ([type]): [description]
|
||||
"""
|
||||
pstr = []
|
||||
for arr in mat:
|
||||
pstr.append(' ' + str(arr))
|
||||
|
||||
print('[\n' + ',\n'.join(pstr) + '\n]')
|
||||
|
||||
def print_linked_list(head):
|
||||
"""Print a linked list
|
||||
|
||||
Args:
|
||||
head ([type]): [description]
|
||||
"""
|
||||
arr = 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):
|
||||
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.
|
||||
"""
|
||||
if root is None:
|
||||
return
|
||||
|
||||
prev_str = ' '
|
||||
trunk = Trunk(prev, prev_str)
|
||||
print_tree(root.right, trunk, True)
|
||||
|
||||
if prev is None:
|
||||
trunk.str = '———'
|
||||
elif is_left:
|
||||
trunk.str = '/———'
|
||||
prev_str = ' |'
|
||||
else:
|
||||
trunk.str = '\———'
|
||||
prev.str = prev_str
|
||||
|
||||
show_trunks(trunk)
|
||||
print(' ' + str(root.val))
|
||||
if prev:
|
||||
prev.str = prev_str
|
||||
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():
|
||||
print(key, '->', value)
|
||||
|
||||
def print_heap(heap):
|
||||
print("堆的数组表示:", heap);
|
||||
print("堆的树状表示:");
|
||||
root = list_to_tree(heap)
|
||||
print_tree(root);
|
||||
18
codes/python/modules/vertex.py
Normal file
18
codes/python/modules/vertex.py
Normal file
@ -0,0 +1,18 @@
|
||||
# File: vertex.py
|
||||
# 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']:
|
||||
""" 输入值列表 vals ,返回顶点列表 vets """
|
||||
return [Vertex(val) for val in vals]
|
||||
|
||||
def vets_to_vals(vets: List['Vertex']) -> List[int]:
|
||||
""" 输入顶点列表 vets ,返回值列表 vals """
|
||||
return [vet.val for vet in vets]
|
||||
Reference in New Issue
Block a user