-
Notifications
You must be signed in to change notification settings - Fork 0
/
Exercise-54-Priority_queue_simple.py
49 lines (36 loc) · 1.15 KB
/
Exercise-54-Priority_queue_simple.py
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
41
42
43
44
45
46
47
48
49
## Priority Queue is an extension of the queue with following properties.
## 1) An element with high priority is dequeued before an element with low priority.
## 2) If two elements have the same priority, they are served according to their order in the queue
## The delete operation has time complexity of O(n)
class PriorityQueue(object):
def __init__(self):
self.queue = []
def __str__(self):
return ' '.join([str(i) for i in self.queue])
## for checking if the queue is empty
def isEmpty(self):
return len(self.queue) == 0
## for inserting an element in the queue
def insert(self, data):
self.queue.append(data)
## for popping an element based on Priority
def delete(self):
try:
max = 0
for i in range(len(self.queue)):
if self.queue[max] < self.queue[i]:
max = i
item = self.queue[max]
del self.queue[max]
return item
except IndexError:
print()
sys.exit()
myQueue = PriorityQueue()
myQueue.insert(12)
myQueue.insert(1)
myQueue.insert(14)
myQueue.insert(7)
print(myQueue)
while not myQueue.isEmpty():
print(myQueue.delete())