|
| 1 | +# Ref: https://github.com/keon/algorithms/blob/master/algorithms/queues/priority_queue.py |
| 2 | + |
| 3 | +import itertools |
| 4 | + |
| 5 | + |
| 6 | +class PriorityQueueNode: |
| 7 | + def __init__(self, data, priority): |
| 8 | + self.data = data |
| 9 | + self.priority = priority |
| 10 | + |
| 11 | + def __repr__(self): |
| 12 | + return f"{self.data}: {self.priority}" |
| 13 | + |
| 14 | + |
| 15 | +class PriorityQueue: |
| 16 | + """An implementation of priority queue using linear array. |
| 17 | + """ |
| 18 | + |
| 19 | + def __init__(self, items=None, priorities=None): |
| 20 | + self.priority_queue_list = [] |
| 21 | + |
| 22 | + if items is None: |
| 23 | + return None |
| 24 | + if priorities is None: |
| 25 | + priorities = itertools.repeat(None) |
| 26 | + |
| 27 | + for item, priority in zip(items, priorities): |
| 28 | + self.push(item, priority=priority) |
| 29 | + |
| 30 | + def __repr__(self): |
| 31 | + return f"PriorityQueue<{repr(self.priority_queue_list)}>" |
| 32 | + |
| 33 | + def size(self): |
| 34 | + return len(self.priority_queue_list) |
| 35 | + |
| 36 | + def push(self, item, priority=None): |
| 37 | + """ |
| 38 | + Push the item into the priority queue. |
| 39 | +
|
| 40 | + If priority is not given, priority is set to the value of item. |
| 41 | + Then the comparison will kinda be like 'John < Alisa' (not accurate!). |
| 42 | + """ |
| 43 | + priority = item if priority is None else priority |
| 44 | + pq_node = PriorityQueueNode(item, priority) |
| 45 | + |
| 46 | + for idx, current in enumerate(self.priority_queue_list): |
| 47 | + if current.priority < pq_node.priority: |
| 48 | + self.priority_queue_list.insert(idx, pq_node) |
| 49 | + |
| 50 | + return None |
| 51 | + |
| 52 | + self.priority_queue_list.append(pq_node) |
| 53 | + |
| 54 | + def pop(self): |
| 55 | + """Remove and return the item with the lowest priority. |
| 56 | + """ |
| 57 | + return self.priority_queue_list.pop().data |
| 58 | + |
| 59 | + |
| 60 | +def main() -> None: |
| 61 | + items = ["John", "Alisa"] |
| 62 | + priorities = [29, 20] |
| 63 | + |
| 64 | + pq = PriorityQueue(items=items, priorities=priorities) |
| 65 | + |
| 66 | + pq.push(item="Bobby", priority=23) |
| 67 | + |
| 68 | + assert str(pq) == "PriorityQueue<[John: 29, Bobby: 23, Alisa: 20]>" |
| 69 | + assert pq.size() == 3 |
| 70 | + assert pq.pop() == "Alisa" |
| 71 | + |
| 72 | + |
| 73 | +if "__main__" == __name__: |
| 74 | + main() |
0 commit comments