File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
HeapQueue_CodingChallenge Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Python code below
2
+ import heapq
3
+
4
+ # Class needed for solution. Do not edit.
5
+ class PriorityQueue :
6
+ def __init__ (self ):
7
+ self .elements = []
8
+
9
+ def is_empty (self ):
10
+ return not self .elements
11
+
12
+ def put (self , item , priority ):
13
+ heapq .heappush (self .elements , (priority , item ))
14
+
15
+ def get (self ):
16
+ return heapq .heappop (self .elements )[1 ]
17
+
18
+ def __str__ (self ):
19
+ return str (self .elements )
20
+
21
+
22
+ def process_tasks (tasks ):
23
+ # Create a priority queue
24
+ pq = PriorityQueue ()
25
+ # Iterate through the tasks
26
+ for task , priority in tasks :
27
+ # Add each task to the priority queue along with its priority value
28
+ pq .put (task , (priority ))
29
+ # Use the "accumulator pattern."
30
+ # Start with an "empty bucket" of the right data type (list in this case)
31
+ # and build the solution by filling the bucket within a loop.
32
+ ordered_task_list = []
33
+
34
+ # Use a while loop with the exit condition that the priority queue is empty.
35
+ # Within this loop, update result with items got from the priority queue.
36
+ while not pq .is_empty ():
37
+ ordered_task_list .append (pq .get ())
38
+
39
+
40
+ return ordered_task_list
You can’t perform that action at this time.
0 commit comments