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) # 36 最小公倍數
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)
9.二維數組根據某一個元素排序
nums = [[1,2,3], [4,6,6]]
nums = sorted(nums, key = lambda x:x[1])
10.字典排序
dic = {'A': 1, 'B': 2, 'C':3}
dic = sorted(dic.items(), key = lambda x:x[0])
11.二分查找代碼模板
nums = [11, 22, 5, 66, 32,48]
left = 0
target = 5
right = len(nums)-1
while left <= right:mid = (left + right) // 2if nums[mid] < target:left = mid + 1elif nums[mid] > target:right = mid - 1else:return mid // 返回下標
12.回溯
全排列
def permute(nums):path = []result = []def backtracking(nums, used):if len(path) == len(nums):result.append(path[:])returnfor i in range(len(nums)):if used[i] == 1:continuepath.append(nums[i])used[i] = 1backtracking(nums, used)used[i] = 0path.pop()backtracking(nums, [0] * len(nums))return result
組合
def combine(n, k):path = []result = []def dfs(n, k, startIndex):if len(path) == k:result.append(path[:])returnfor i in range(startIndex, n+1):path.append(i)dfs(n, k, i+1)path.pop()dfs(n, k, 1)return result
13.前綴和
用來快速求出某一個區間的和
nums = [1, 2, 3, 4, 5]
s = [0] * (len(nums)+1)
for i in range(1, len(nums)+1):s[i] = nums[i-1] + s[i-1]
result = s[r] - s[l-1] # 求出[l, r] 的區間和
14.求兩個時間有多少個星期一
import datetime
from datetime import timedelta
t1 = datetime(2025, 4, 1)
t2 = datetime(2000, 1, 1)
count = 0
current = t2
while current <= t1:if currnt.weekday() == 0: // 判斷星期幾count += 1current += timedelta(days=1) // 天數加一
print(count)