一、数学与数值计算

  1. math 模块提供基础数学函数,适合快速计算:

    import math
    print(math.gcd(12, 18))         # 最大公约数 → 6
    print(math.comb(5, 2))          # 组合数 C(5,2) → 10
    print(math.isqrt(10))           # 整数平方根 → 3
    
  2. fractions 模块
    处理分数运算,避免浮点误差:

    from fractions import Fraction
    a = Fraction(3, 4)  # 3/4
    

二、高效数据结构

  1. heapq快速实现优先队列(Dijkstra 算法等):

    import heapq
    heap = []
    heapq.heappush(heap, 3)
    heapq.heappop(heap)  # 弹出最小值
    
  2. bisect 二分查找维护有序列表:

    import bisect
    arr = [1, 3, 5]
    bisect.insort(arr, 4)  # 插入后保持有序 → [1, 3, 4, 5]
    
  3. collections 增强容器

    • deque: 双端队列(BFS 首选)
      from collections import deque
      dq = deque()
      dq.appendleft(1)  # O(1) 左端插入
      
    • defaultdict: 默认字典
      from collections import defaultdict
      d = defaultdict(int)  # 键不存在时返回 int() 即 0
      
    • Counter: 频率统计
      from collections import Counter
      cnt = Counter("abracadabra")
      print(cnt['a'])  # 出现次数 → 5
      

三、迭代工具与排列组合

  1. itertools 模块
    • 排列组合生成:
      import itertools
      list(itertools.permutations([1,2,3], 2))  # 所有排列
      list(itertools.combinations([1,2,3], 2))   # 所有组合
      
    • 高效迭代:
      itertools.product('AB', repeat=2)  # 笛卡尔积 → AA, AB, BA, BB
      

四、输入输出加速

  1. sys.stdin 快速读取
    处理大规模输入时显著提升速度:
    import sys
    input = sys.stdin.readline  # 替换默认 input
    n = int(input())
    arr = list(map(int, input().split()))
    

五、记忆化与缓存

  1. functools.lru_cache
    递归函数缓存(动态规划优化):
    from functools import lru_cache
    @lru_cache(maxsize=None)
    def fib(n):
        return fib(n-1) + fib(n-2) if n > 1 else n
    

六、其他技巧

  • 列表推导式:快速生成数据结构
    matrix = [[0]*n for _ in range(n)]  # 避免浅拷贝问题
    
  • 大数处理:Python 原生支持大整数运算,无需额外库。

注意事项

  • 禁用第三方库:如 numpy, pandas 在多数比赛中不允许使用。
  • 空间优化:Python 内存消耗较大,需注意数据规模。
  • 算法适配:Python 的递归深度有限(默认约 1000),深递归需改用迭代或设置 sys.setrecursionlimit()

掌握这些库和技巧可以大幅提升代码效率和简洁性,但核心仍是算法的正确性与时间复杂度分析。