Python_语法糖
本篇文章是转专业机考前抱佛脚所写,可能有点马虎和功利。
itertools 全排列和全组合
combinations
和permutations
两者都是itertools
中的函数,可以实现生成字符串、字典、列表,元组中的排列和组合后的元素,形式为元组。先从itertools
中引入。
1 | from itertools import combinations,permutations |
另外,全排列和全组合也可以通过dfs
实现
1 | def dfs(u):#全排列 |
functools_排序
cmp_to_key
将比较函数改为key函数
1 | import functools |
collections
deque
用于实现单调队列和双端队列
1 | from collections import deque |
defautdict
初始化字典,免去了初始赋值
1
2
3
4from collections import defaultdict
d = defaultdict(int)# 初始化类型,int,str,list...
print(d)
# defaultdict(<class 'int'>, {})
计算相关
最大公约数和最小公倍数
math
库提供了gcd
函数用于求最大公约数:
1 | from math import gcd |
对于最小公倍数,由于lcm
和gcd
存在以下关系,
$$
LCM(a, b) = abs(ab) // GCD(a, b)
$$
1 | from math import gcd |
约分化简
1 | from fractions import Fraction |
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 loading233!