1. 全排列 - itertools.permutations
注:Python产生的全排列是会含有重复的项的!并且当且仅当输入的列表是升序的,结果才是按字典序的!
from itertools import permutations
a = [1, 2, 4]
perm = permutations(a)
print(type(perm))
''' <class 'itertools.permutations'> '''
for item in perm:
print(item)
'''
(1, 2, 4)
(1, 4, 2)
(2, 1, 4)
(2, 4, 1)
(4, 1, 2)
(4, 2, 1)
'''
b = [1, 2, 2, 3]
for item in permutations(b):
print(item)
'''
(1, 2, 2, 3)
(1, 2, 3, 2)
(1, 2, 2, 3)
(1, 2, 3, 2)
(1, 3, 2, 2)
(1, 3, 2, 2)
(2, 1, 2, 3)
(2, 1, 3, 2)
(2, 2, 1, 3)
(2, 2, 3, 1)
(2, 3, 1, 2)
(2, 3, 2, 1)
(2, 1, 2, 3)
(2, 1, 3, 2)
(2, 2, 1, 3)
(2, 2, 3, 1)
(2, 3, 1, 2)
(2, 3, 2, 1)
(3, 1, 2, 2)
(3, 1, 2, 2)
(3, 2, 1, 2)
(3, 2, 2, 1)
(3, 2, 1, 2)
(3, 2, 2, 1)
'''
2. 双向队列 - collections.deque
from collections import deque
a = deque()
a.append(2)
a.append(3)
a.append(4)
a.appendleft(1)
print(a)
''' deque([1, 2, 3, 4]) '''
print(a.pop())
''' 4 '''
print(a.popleft())
''' 1 '''
print(a)
''' deque([2, 3]) '''
3. 优先队列 - heapq
import heapq
# heappush():入队
# heappop():出队
arr = [1, 4, 2, 8, 5, 7]
heap = []
for val in arr:
heapq.heappush(heap, val)
while heap:
print(heapq.heappop(heap))
'''
1
2
4
5
7
8
'''
# heapify():将数组原地转化为优先队列
# heap[0]:获取最小元素
arr = [1, 4, 2, 8, 5, 7]
heapq.heapify(arr)
print(arr[0])
while arr:
print(heapq.heappop(arr))
'''
1
2
4
5
7
8
'''
本文深入探讨Python中三种重要的数据结构与算法:全排列生成、双向队列操作及优先队列应用。通过具体代码实例,详细解析了itertools.permutations生成全排列、collections.deque实现双向队列及heapq构建优先队列的方法。
3万+

被折叠的 条评论
为什么被折叠?



