first step

1
2
sys.setrecursionlimit(50000)		#设置递归深度
input = lambda: sys.stdin.readline().strip() #快读

精度控制

1
2
3
4
5
6
import math
math.ceil(3.2) # 4 (向上)
math.floor(3.9) # 3 (向下)

round(number, ndigits) #舍入的数字,保留的尾数位数
f"{num:.2f}" #保留两位小数

字符串操作

1
2
3
4
5
6
7
8
# 字符检测
a[i].isdigit()
a[i].isalpha()
# 字符串大小写转化
str.upper()
str.lower()
# 字符串反转
rev = s[::-1]

处理交集并集

1
2
首先转化为set
&|-+

bisect 二分查找

1
2
3
4
import bisect

bisect.bisect_left返回第一个​​大于等于​​x的位置
bisect.bisect_right返回第一个​​大于​​x的位置

二维矩阵快速输出

1
2
for i in range(1, n+1):
print(' '.join(map(str, arr[i][1:m+1])))

datetime

1
2
3
4
5
6
7
8
from datetime import datetime, timedelta

# 时间差计算
start = datetime(2023,1,1)
end = start + timedelta(days=7) # 2023-01-08

# 解析字符串
dt = datetime.strptime("20230101", "%Y%m%d")

re

math

1
2
3
4
5
math.gcd(a,b)  #最大公约数,若有负数先取abs()
math.sqrt(x) #开方
math.pow(x, y) #x^y
math.pi() #pai
math.inf() #无穷

四舍五入

1
2
3
round()    					  #奇进偶舍
math.ceil() #向上取整
math.floor() #向下取整

排序

1
2
3
4
5
words = ["apple", "banana", "cherry"]
sorted_by_length = sorted(words, key=len) # 按长度排序: ['apple', 'cherry', 'banana']

items = [("A", 1), ("B", 1), ("C", 2)]
sorted_items = sorted(items, key=lambda x: x[1]) # ("A",1)和("B",1)保持原顺序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
graph = {}
n = int(input().strip())
for i in range(n-1):
a, b = map(int, input().split())
if a not in graph:
graph[a] = [b]
else:
graph[a].append(b)
### 存储无向图
if b not in graph:
graph[b] = [a]
else:
graph[b].append(a)
# 初始化状态数组
st = [False for i in range(n+1)]

def dfs(u):
st[u] = True

for i in range(graph[u]):
if not st[i]:
dfs(i)

并查集

1
2
3
4
5
6
7
8
9
p = [i for i in range(n+1)]
size = [1] * (n+1) # 按秩合并

# 非递归find
def find(x):
while p[x] != x:
p[x] = p[p[x]] # 路径压缩
x = p[x]
return p[x]