-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathqueue.txt
More file actions
58 lines (41 loc) · 964 Bytes
/
queue.txt
File metadata and controls
58 lines (41 loc) · 964 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# Queue
## collections.dequeue
* queue: only supports removing elements from the back
* dequeue: also supports removing elements form the front
import collections
q = collections.deque([1, 2, 3], maxlen=None)
q.append(4)
q.extend([5, 6])
while q:
print(q.popleft())
## queue.Queue
* Used for synchronizing threads
* thread-safe
* Use collections.dequeue otherwise
import queue
q = queue.Queue(maxsize=0)
q.put(1)
q.put(2)
while not q.empty():
print(q.get())
# Priority queue
## heapq
* see heapq.txt
q = []
heapq.heappush(q, 3)
heapq.heappush(q, 1)
heapq.heappush(q, 2)
q = [3, 1, 2]
heapq.heapify(q) // in-place
while q:
print(heapq.heappop(q))
## queue.PriorityQueue
* For threads (like queue.Queue)
* Wrapper around heapq
pq = queue.PriorityQueue()
pq.put((1, "Task 1"))
pq.put((3, "Task 3"))
pq.put((2, "Task 2"))
print(pq.get()) # Output: (1, 'Task 1')
print(pq.get()) # Output: (2, 'Task 2')
print(pq.get()) # Output: (3, 'Task 3')