1.保留k位小数
round(10/3, 2) # 第二个参数表示保留几位小数
2.输入代替方案(加速读取)
import sys
n= int(sys.stdin.readline()) # 读取整数(不加int就是字符串)
a, b = map(int, sys.stdin.readline().split()) # 一行读取多个数
3.数学计算
import math
math.gcd((12, 18)) # 最大公约数
math.pow(2,3) # 2的三次方
math.comb(5,2) # 10组合数
math.lcm(12, 18) # 26 最小公倍数
bin(10) # 十进制转二进制
hex(255) # 十进制转16进制
int('1010', 2) # 求1010的十进制
int('A', 16) # 求A的十进制
4.双端队列
from collections import deque
dq = deque()
dq.appendleft() # 左侧加入
dp.pop() # 右侧弹出
5.集合操作
a = {1, 2}
b = {2, 3}
a & b # 交集
a | b # 并集
6.字符串处理
import re
re.findall(r'\d+', 'a1b22c') # ['1', '22']
s.isdigit() #判断是否是数字
5.文件操作
with open('input.txt', 'r') as f:
data = f.readlines() # 读取全部内容
6.二分查找
import bisect
arr = [1,3,5]
bisect.insort(arr, 4) # [1,3,4,5]
pos = bisect.bisect_left(arr, 3) # 输出 1(第一个3的位置)
7.排列组合相关API
// 1.计算组合数
import math
math.comb(5, 2)
// 2.计算排列数
math.perm(5, 2)
// 3.生成所有的组合数
import itertools
list(itertools.combinations([1,2,3,4], 2))
// 4.生成所有排列数
list(itertools.permutations([1, 2, 3, 4]), 2)
8.列表转字符串
nums = ['a', 'b', 'c']
print(''.join(nums))
9.字符串大小写转换
a = "abcd"
print(a,upper, a.lower)
a.swapcase() # 大小写翻转转换
s.isalpha() # 判断是否都是字母
10.lamda使用
h = [[1, 2], [3, 1]]
sorted(h, key=lambda x:x[0], reverse=True)
11.chr/ord转换
print(chr(97), ord('a')) # a 97
12.Counter计数器
from collections import Counter
nums = ['a', 'b', 'b', 'c', 'c', 'c']
nums_new = Counter(nums)
print(nums_new) # 输出结果:Counter({'c': 3, 'b': 2, 'a': 1})
nums_new['d'] = 1 # Counter({'c': 3, 'b': 2, 'a': 1, 'd': 1})
print(d1.keys())
print(d1.values)
print(d1.items)
13.accumulate累加
from itertools import accumulate
a = [1,2,3,4]
print(list(accumulate(a))) # [1, 3, 6, 10]
14.判断质数
def isPrim(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5)+1):
if n % i == 0:
return False
return True
15.二分
from bisect import *
pos = bisect_left(nums, 2) # 查找左侧插入点
insort(nums, 4) # 有序插入元素到列表中
16.闰年判断
import calendar
calendar.isleap(2022)
calendar.leapdays(2000, 2020) # 统计闰年总数
17.集合操作
s1 = {1, 2, 3}
s2 = {3, 4, 5}
print(s1 | s2) # 并集
print(s1 & s2) # 交集
18.动态规划模板
dp = [0] * (N+1)
for i in range(M): # 物品
for j in range(N, weights[i]-1, -1): # 重量
dp[j] = max(dp[j], dp[j-weights[i]]+values[i])