File tree Expand file tree Collapse file tree 3 files changed +57
-0
lines changed Expand file tree Collapse file tree 3 files changed +57
-0
lines changed Original file line number Diff line number Diff line change @@ -45,6 +45,7 @@ $ coverage report -m
45
45
* [ Lose/Lose Hash Function] ( structures/hash_map.py )
46
46
* [ Heap] ( structures/heap.py )
47
47
* [ Trie] ( structures/trie.py )
48
+ * [ Priority Queue] ( structures/priority_queue.py )
48
49
49
50
### Algorithms
50
51
Original file line number Diff line number Diff line change
1
+ import itertools
2
+ from heapq import heappush , heappop
3
+
4
+ class PriorityQueue ():
5
+
6
+ pq = []
7
+ mapper = {}
8
+ REMOVED = '__removed-task__'
9
+ counter = itertools .count ()
10
+
11
+ def __init__ (self ):
12
+ pass
13
+
14
+ def add_task (self , task , priority = 0 ):
15
+ if task in self .mapper :
16
+ self .remove_task (task )
17
+ count = next (self .counter )
18
+ entry = [priority , count , task ]
19
+ self .mapper [task ] = entry
20
+ heappush (self .pq , entry )
21
+
22
+ def remove_task (self , task ):
23
+ entry = self .mapper .pop (task )
24
+ entry [- 1 ] = self .REMOVED
25
+
26
+ def pop_task (self ):
27
+ while self .pq :
28
+ _ , _ , task = heappop (self .pq )
29
+ if task is not self .REMOVED :
30
+ del self .mapper [task ]
31
+ return task
32
+ raise KeyError ('Pop from empty priority queue.' )
Original file line number Diff line number Diff line change
1
+ import unittest
2
+ from structures .priority_queue import PriorityQueue
3
+
4
+ class TestPriorityQueue (unittest .TestCase ):
5
+
6
+ def test_pq_simple (self ):
7
+ pq = PriorityQueue ()
8
+ pq .add_task ('drive to work' , 2 )
9
+ pq .add_task ('get keys' )
10
+ pq .add_task ('load car' , 1 )
11
+ pq .add_task ('check gas' , 1 )
12
+ pq .add_task ('turn on car' , 1 )
13
+ pq .add_task ('park at work' , 3 )
14
+ pq .remove_task ('load car' )
15
+ pq .add_task ('check gas' , 1 )
16
+
17
+ self .assertEqual ('get keys' ,pq .pop_task ())
18
+ self .assertEqual ('turn on car' , pq .pop_task ())
19
+ self .assertEqual ('check gas' , pq .pop_task ())
20
+ self .assertEqual ('drive to work' , pq .pop_task ())
21
+ self .assertEqual ('park at work' , pq .pop_task ())
22
+
23
+ with self .assertRaises (KeyError ):
24
+ pq .pop_task ()
You can’t perform that action at this time.
0 commit comments