forked from clair3st/Data-Structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpriorityq.py
More file actions
40 lines (31 loc) · 1.19 KB
/
priorityq.py
File metadata and controls
40 lines (31 loc) · 1.19 KB
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
"""Python implementation of a priorityq."""
from src.binheap import Binheap
class PriorityQ(object):
"""
Priority Q data structure.
Following methods are supported.
Insert(value, [priority]): inserts a value into the queue.
Takes an optional argument for that value's priority.
pop(): removes the most important item from the queue
and returns its value.
peek(): returns the most important item without removing it from the queue.
"""
def __init__(self):
"""Initialize priorityq."""
self._container = Binheap()
def insert(self, val, priority=0):
"""Insert a val into the queue with an argument for the priority."""
self._container.push((priority, val))
def pop(self):
"""Remove the most important item from the queue."""
to_return = self._container.container[1][1]
if not to_return:
raise(IndexError, 'Can\'t pop from an empty queue.')
self._container.pop()
return to_return
def peek(self):
"""Return the most important item without removing it."""
try:
return self._container.container[1][1]
except IndexError:
return None