递归深度
import sys
sys.setrecursionlimit(100000)
全排列
import itertools
numbers = [i for i in range(1, 4)]
for num in itertools.permutations(numbers, 3):
print(num)
栈、队列、双端队列:
from collections import deque
st = deque()
q = deque()
dq = deque()
优先队列:
from heapq import *
pq = [3, 2]
heapify(pq)
heappush(pq, 4)
heappush(pq, 1)
print(heappop(pq))
print(heappop(pq))
print(heappop(pq))
print(heappop(pq))
附:自定义比较(极特殊情况)
一般情况考虑取负号,对于str可以使用reversed或者str[::-1]
from heapq import *
class Per:
def __init__(self, name, score):
self.name = name
self.score = score
def __lt__(self, other): ## __lt/le/eq/ne/gt/ge__
return self.score > other.score or self.score == other.score and self.name < other.name
def __str__(self):
return "{}: {}".format(self.name, self.score)
def __repr__(self):
return "Per({}, {})".format(self.name, self.score)
# 分数从大到小,姓名从小到大
pq = []
heapify(pq)
heappush(pq, Per('Tom', 98))
heappush(pq, Per('Mike', 60))
heappush(pq, Per('Kitty', 60))
print(heappop(pq))
print(heappop(pq))
print(heappop(pq))