python–leetcode–常用模块和方法
itertools系列
permutations用于排列
combinations用于组合
from itertools import permutations, combinations
# 本身返回的是迭代器
a = [1,2,3]
pe = list(permutations(a))
#排列[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
com = list(combinations(a,2)) # 组合个数为2
#组合[(1, 2), (1, 3), (2, 3)]
collections系列
计数器(Counter):返回每个元素个数,字典类型
双向队列(deque):队列,可以对队首进行操作
默认字典(defaultdict):包含int,list,set
from collections import Counter, deque, defaultdict
#计数器(Counter)
a = [1,2,1,1,2,3,3,3,3]
a_count = Counter(a)
#Counter({3: 4, 1: 3, 2: 2})
#双向队列(deque)
a_deque = deque(a)
a_deque.popleft()
a_deque.appendleft(0)
#deque([0, 2, 1, 1, 2, 3, 3, 3, 3])
#默认字典(defaultdict)
a = [1,2,1]
hash_list = defaultdict(list)#列表字典
for i in range(3):
hash_list[a[i]].append('*')
#defaultdict(<class 'list'>, {1: ['*', '*'], 2: ['*']})
hash_int = defaultdict(int)#用来计数
for k in a:
hash_int[k] += 1
#defaultdict(<class 'int'>, {1: 2, 2: 1})
hash_set = defaultdict(set)#集合字典
for i in range(3):
hash_set[a[i]].add('*')
#defaultdict(<class 'set'>, {1: {'*'}, 2: {'*'}})
堆heapq
顶堆:保持一种完全二叉树结构,小顶堆保持堆顶元素小于左子树和右子树的元素值
from heapq import heappush, heappop, heapify
a = [1, 3, 2, 5, 0]
heapify(a) # 默认创建小顶堆
print(a[0]) # 0
heappush(a, -1) # 增加元素到堆
print(a[0]) # -1
heappop(a) # 弹出堆头
print(a[0]) # 0