Today i will be implementing Queue Data Structure using Python.
Before we will go to Coding , lets try to understand what is Queue data structure.
Queue Data Structures. Queue is also an abstract data type or a linear data structure , in which the first element is inserted from one end called REAR(also called tail), and the deletion of existing element takes place from the other end called as FRONT(also called head).So it works on FIFO principle.
One may ask what is importance of queue and where it can be used.?
Queue is a data structure . One of the practical example we can take to understand the same is the way printers are used.
Assume we have printer in shared network, so everybody send there request for printing.
So it should print for the request which came first.
Lets try to implement the same via Python .
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'''This is the implementation of queue''' | |
class Queue(): | |
def __init__(self): | |
self.que=[] | |
def enqueue(self,data): | |
''' This will insert element in Queue''' | |
self.que.append(data) | |
def dequeue(self): | |
''' This will remove element in Queue''' | |
try: | |
self.que.remove(self.que[0]) | |
except IndexError: | |
print('Please Enqueue before Dequeue') | |
def isEmpty(self): | |
''' This will tell you if queue is empty or not''' | |
if len(self.que): | |
return False | |
else: | |
return True | |
def find(self,data): | |
''' Method to test if element exist inside Queue''' | |
self.exist_in_queue='N' | |
for i in range(len(self.que)): | |
if i==data: | |
return True | |
else: | |
self.exist_in_queue='N' | |
if self.exist_in_queue=='N': | |
return False | |
So i have created a class with name Queue .
On creation of object of this class , will create array que which will hold our data.
The method Enqueue will add element to this array.
The Dequeue will remove the element from position zero , so which means the element which has been added first will be removed and this process will go subsequently.
The other methods which i have implemented is isEmpty() and find() , which is to check if the queue is empty or not not.
While find will check if the data exist in our queue or not.
No comments:
Post a Comment