Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2622bb4

Browse files
author
Amogh Singhal
authored
Create priority_queue_simple.py
1 parent 44644bf commit 2622bb4

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

‎priority_queue_simple.py‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Priority Queue is an extension of the queue with following properties.
2+
# 1) An element with high priority is dequeued before an element with low priority.
3+
# 2) If two elements have the same priority, they are served according to their order in the queue
4+
5+
class PriorityQueue(object):
6+
def __init__(self):
7+
self.queue = []
8+
9+
def __str__(self):
10+
return ' '.join([str(i) for i in self.queue])
11+
12+
# for checking if the queue is empty
13+
def isEmpty(self):
14+
return len(self.queue) == 0
15+
16+
# for inserting an element in the queue
17+
def insert(self, data):
18+
self.queue.append(data)
19+
20+
# for popping an element based on Priority
21+
def delete(self):
22+
try:
23+
max = 0
24+
25+
for i in range(len(self.queue)):
26+
if self.queue[max] < self.queue[i]:
27+
max = i
28+
29+
item = self.queue[max]
30+
del self.queue[max]
31+
32+
return item
33+
34+
except IndexError:
35+
print()
36+
sys.exit()
37+
38+
myQueue = PriorityQueue()
39+
myQueue.insert(12)
40+
myQueue.insert(1)
41+
myQueue.insert(14)
42+
myQueue.insert(7)
43+
44+
print(myQueue)
45+
46+
while not myQueue.isEmpty():
47+
print(myQueue.delete())
48+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /