In python, which satisfies the conditions below A \"CircularQueue\" is an abstra
ID: 3748219 • Letter: I
Question
In python, which satisfies the conditions below
A "CircularQueue" is an abstract data type for storing a collection of items, where items are added to one end and removed from the opposite end of the collection. The methods for adding and removing items from a queue are traditionally called "enqueue(" and "dequeue)" respectively Complete and test a CircularQueue implementation. Exceptions are raised when preconditions are violated. For example, an IndexError will be raised if a client program attempt to dequeue from an empty queue or to enqueue from a full queue. Implement the dequeue(), enqueue(), peek() methods of the CircularQueue class to raise an IndexError in the above error situations You should include the entire CircularQueue class definition in your answer to this question. Use the implementation of the CircularQueue discussed in lecturers as a basis for your implementation For example Test Result try: q-CircularQueue(5) q.enqueue (2) print (q.dequeue)) except IndexError as err print (err) try: The queue is empty q - CircularQueue (10) print (q.dequeue)) except IndexError as err: print (err) try: The queue is full qCircularQueue (5) q.enqueue(12) q.enqueue(17) q.enqueue (25) q.enqueue (11) q.enqueue (9) q.enqueue (3) print (q.dequeue()) except IndexError as err: print (err)Explanation / Answer
class CircularQueue:
#Constructor
def __init__(self):
self.queue = list()
self.head = 0
self.tail = 0
self.maxSize = 8
#Adding elements to the queue
def enqueue(self,data):
if self.size() == self.maxSize-1:
return ("Queue Full!")
self.queue.append(data)
self.tail = (self.tail + 1) % self.maxSize
return True
#Removing elements from the queue
def dequeue(self):
if self.size()==0:
return ("Queue Empty!")
data = self.queue[self.head]
self.head = (self.head + 1) % self.maxSize
return data
#Calculating the size of the queue
def size(self):
if self.tail>=self.head:
return (self.tail-self.head)
return (self.maxSize - (self.head-self.tail))
q = CircularQueue()
print(q.enqueue(1))
print(q.enqueue(2))
print(q.enqueue(3))
print(q.enqueue(4))
print(q.enqueue(5))
print(q.enqueue(6))
print(q.enqueue(7))
print(q.enqueue(8))
print(q.enqueue(9))
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.