!!!一定要养成良好的代码习惯
!!变量值不能混用
!!代码不能找不到
排序
字典 按值
lis=sorted(nam.items(),key=lambda x:(int(x[1][0]),-(x[1][1])),reverse=True)
列表
res=sorted(human,key=lambda human:(human[1],-human[2]),reverse=True)
字典值 为列表、集合
from collections import defaultdict
s=defaultdict(set)
值和下标对应
index={s:i for i,s in enumerate(list1)}
善用
list.index()
树的定义
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
先序和中序构造树(参照leetcode)
def buildTree(inorder, postorder) -> TreeNode:
def helper(in_left, in_right):
# 如果这里没有节点构造二叉树了,就结束
if in_left > in_right:
return None
# 选择 post_idx 位置的元素作为当前子树根节点
val = postorder.pop()
root = TreeNode(val)
# 根据 root 所在位置分成左右两棵子树
index = idx_map[val]
# 构造右子树
root.right = helper(index + 1, in_right)
# 构造左子树
root.left = helper(in_left, index - 1)
return root
idx_map = {val:idx for idx, val in enumerate(inorder)}
return helper(0, len(inorder) - 1)
中序和后序
def buildTree(inorder, preorder) -> TreeNode:
if not preorder:
return None
root = TreeNode(preorder[0])
stack = [root]
inorderIndex = 0
for i in range(1, len(preorder)):
preorderVal = preorder[i]
node = stack[-1]
if node.val != inorder[inorderIndex]:
node.left = TreeNode(preorderVal)
stack.append(node.left)
else:
while stack and stack[-1].val == inorder[inorderIndex]:
node = stack.pop()
inorderIndex += 1
node.right = TreeNode(preorderVal)
stack.append(node.right)
return root
大小写 转换
ord()
chr()
字符串相关
str.isdigit()#字符串是否只包含数字
str.capitalize()#字符第一个字符大写
str.center(width)#返回一个原字符串居中,并使用空格填充至长度 width 的新字符串
str.isalpha()#如果 string 至少有一个字符并且所有字符都是字母则返回 True,否则返回 False
str.islower()
str.isnumeric()
str.join()
str.swapcase()
str.replace()
字典
res[i]=max(s.get(i,0),s[k[j]]+res[i-k[j]])
并查集模板
class UnionFind:
def __init__(self):
"""
记录每个节点的父节点
"""
self.father = {}
def find(self,x):
"""
查找根节点
路径压缩
"""
root = x
while self.father[root] != None:
root = self.father[root]
# 路径压缩
while x != root:
original_father = self.father[x]
self.father[x] = root
x = original_father
return root
def merge(self,x,y,val):
"""
合并两个节点
"""
root_x,root_y = self.find(x),self.find(y)
if root_x != root_y:
self.father[root_x] = root_y
def is_connected(self,x,y):
"""
判断两节点是否相连
"""
return self.find(x) == self.find(y)
def add(self,x):
"""
添加新节点
"""
if x not in self.father:
self.father[x] = None
python中IDLE一些比较常用的快捷键有:
加缩进 | Ctrl+] |
---|---|
减缩进 | Ctrl+[ |
加注释 | Alt+3 |
去注释 | Alt+4 |
上一条命令 | Alt+p |
下一条命令 | Alt+n |
Enter | 鼠标选中后进行复制 |
zip函数
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c) # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped) # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
[(1, 2, 3), (4, 5, 6)]
a= ["ca","bb","ac"]
for col in zip(*a):
print(col)
('c', 'b', 'a')
('a', 'b', 'c')
统计列表中字符出现次数
#统计列表中字符出现次数
>>> import collections
>>> a=[1,2,534,3,2,5,4]
>>> cout=collections.Counter(a)
>>> cout
Counter({2: 2, 1: 1, 534: 1, 3: 1, 5: 1, 4: 1})
DijkstraRoad最短路径
def DijkstraRoad(sNode, dNode, adjacencyMatrix):
path = [] # s-d的最短路径
n = len(adjacencyMatrix) # 邻接矩阵维度,即节点个数
fmax = 999
w = [[0 for i in range(n)] for j in range(n)] # 邻接矩阵转化成维度矩阵 n*n阶矩阵
book = [0 for i in range(n)] # 是否已经是最小的标记列表
dis = [fmax for i in range(n)] # s到其他节点的最小距离
book[sNode] = 1
midpath = [-1 for i in range(n)] # 上一跳列表
for i in range(n):
for j in range(n):
if adjacencyMatrix[i][j] != 0:
# i,j间有路径
w[i][j] = adjacencyMatrix[i][j]
else:
# i,j间没路径
w[i][j] = fmax
if i == sNode and adjacencyMatrix[i][j] != 0:
dis[j] = adjacencyMatrix[i][j] # i,j的距离
for i in range(n - 1): # n-1次遍历,除了s节点
min = fmax
u = 0
for j in range(n):
if book[j] == 0 and dis[j] < min: # 如果未遍历且距离最小
min = dis[j]
u = j
book[u] = 1
for v in range(n): # u直连的节点遍历一遍
if dis[v] > dis[u] + w[u][v]:
dis[v] = dis[u] + w[u][v]
midpath[v] = u # 上一跳更新
j = dNode # j是序号
path.append(dNode) # 因为存储的是上一跳,所以先加入目的节点d,最后倒置
while (midpath[j] != -1):
path.append(midpath[j])
j = midpath[j]
path.append(sNode)
path.reverse() # 倒置列表
return path, dis[dNode]