python–leetcode–常用模块和方法

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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柴寺仓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值