-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueue implementation using Python List
124 lines (108 loc) · 2.95 KB
/
Queue implementation using Python List
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# B:QUEUES:
#B-1:Array implementation of QUEUES
#B-1-a:Dyanmic length
class QueueEmptyError(Exception):
pass
class Queue:
def __init__(self):
self.item=[]
def is_empty(self):
return self.item==[]
def size(self):
return len(self.item)
def enqueue(self,data):
self.item.append(data)
def dequeue(self):
if self.is_empty():
raise QueueEmptyError("Queqe is empty!!")
return self.item.pop(0)
def peek(self):
if self.is_empty():
raise QueueEmptyError("Queue is empty!!")
return self.item[0]
def display(self):
print(self.item)
if __name__=="__main__":
queue=Queue()
while True:
print("1.Enqueue")
print("2.Dequeue")
print("3.Size")
print("4.Peek")
print("5.Display")
print("6.Quit")
choice=int(input("Enter a choice: "))
if(choice==1):
data=int(input("Enter the element: "))
queue.enqueue(data)
elif(choice==2):
popped=queue.dequeue()
print("Delete elements is: ",popped)
elif(choice==3):
s=queue.size()
print("Size is: ",s)
elif(choice==4):
p=queue.peek()
print("Front is at: ",p)
elif(choice==5):
queue.display()
elif(choice==6):
break
else:
print("Invalid Choice!!")
print()
#B-1-b:Efficient implementation for queue:
class QueueEmptyError(Exception):
pass
class Queue:
def __init__(self):
self.item=[]
self.front=0
def is_empty(self):
return self.front==len(self.item)
def size(self):
return len(self.item)-self.front
def enqueue(self,data):
self.item.append(data)
def dequeue(self):
if self.is_empty():
raise QueueEmptyError("Queue is empty..")
f=self.item[self.front]
self.item[self.front]=None
self.front+=1
return f
def peek(self):
if self.is_empty():
raise QueueEmptyError("Empty!")
return self.item[self.front]
def display(self):
print(self.item)
if __name__=="__main__":
queue=Queue()
while True:
print("1.Enqueue")
print("2.Dequeue")
print("3.Size")
print("4.Peek")
print("5.Display")
print("6.Quit")
choice=int(input("Enter a choice: "))
if(choice==1):
data=int(input("Enter the element: "))
queue.enqueue(data)
elif(choice==2):
popped=queue.dequeue()
print("Delete elements is: ",popped)
elif(choice==3):
s=queue.size()
print("Size is: ",s)
elif(choice==4):
p=queue.peek()
print("Front is at: ",p)
elif(choice==5):
queue.display()
elif(choice==6):
break
else:
print("Invalid Choice!!")
print()