Skip to content

Instantly share code, notes, and snippets.

@wakoliVotes
Last active February 21, 2022 08:43
Show Gist options
  • Save wakoliVotes/52ee4e8a9478543be58c705c9bf603ee to your computer and use it in GitHub Desktop.
Save wakoliVotes/52ee4e8a9478543be58c705c9bf603ee to your computer and use it in GitHub Desktop.
# Implementation of the FIFO Property using Python Queues
# Class definition
class QueueData:
# An empty queue that will store the elements
def __init__(self):
self.data = []
# enqueue() method
# Adding the first element e to the queue
def enqueue(self, e):
self.data.insert(0, e)
# dequeue() method
# Removing and returning the element from the front (FIFO)
# Raise an exception if the queue is empty
def dequeue(self):
if self.is_empty():
raise IndexError("Queue is empty")
else:
return self.data.pop()
# peek() method
# Returning the first element of the queue
# Raise exception if the queue is empty
def peek(self):
if self.is_empty():
raise IndexError("Queue is Empty")
else:
return self.data[-1]
# size() method
# Returning True if the Queue is Empty
def is_empty(self):
return len(self.data) == 0
# Returning the number of elements in the Queue
def size(self):
return len(self.data)
# Object Instantiation and Queue Implementations
Q = QueueData()
Q.enqueue("M") # M
Q.enqueue("O") # O
Q.enqueue("N") # N
Q.enqueue("D") # D
Q.enqueue("A") # A
Q.enqueue("Y") # Y
print(Q.peek())
print(Q.size())
print(Q.is_empty())
print(Q.dequeue()) # M
print(Q.dequeue()) # O
print(Q.dequeue()) # N
print(Q.dequeue()) # D
print(Q.dequeue()) # A
print(Q.dequeue()) # Y
print(Q.is_empty()) # True
print(Q.size()) # 0
print(Q.peek()) # IndexError: Queue is Empty
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment