Skip to content

Commit 969a632

Browse files
Merge pull request #5 from ahmedabougabal/priority_queue
Feat: adds the solution to the maze, implementing commented out tasks
2 parents 7c69630 + e11c5e1 commit 969a632

File tree

1 file changed

+40
-0
lines changed
  • HeapQueue_CodingChallenge

1 file changed

+40
-0
lines changed

HeapQueue_CodingChallenge/pq.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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

0 commit comments

Comments
 (0)