Question: Modify the CircularQueue class so the capacity automatically increases when you exceed the current capacity. When you try to add an item to
Modify the "CircularQueue" class so the capacity automatically increases when you exceed the current capacity. When you try to add an item to a full queue, the capacity should be doubled.
Do not decrease the capacity of the queue when you remove items from the queue.
You should include the entire CircularQueue class definition in your answer to this question.
For example:
q = CircularQueue(2) q.enqueue(10) q.dequeue() q.enqueue(20) q.enqueue(30) q.enqueue(40) print(q.size()) print(q.dequeue()) print(q.dequeue()) print(q.dequeue())
Result
3
20
30 40
Original Code:
class CircularQueue: def __init__(self,capacity):
self.items =[None]*capacity self.MAX_QUEUE = capacity self.front = 0 self.back = self.MAX_QUEUE - 1 self.count = 0
def is_full(self): return self.count == self.MAX_QUEUE
def is_empty(self): return self.count == 0
def enqueue(self,item): if not self.is_full(): self.back = (self.back+1) % self.MAX_QUEUE self.items[self.back] = item self.count +=1 else: raise IndexError("The queue is full.") def dequeue(self): if not self.is_empty(): item = self.items[self.front] self.front =(self.front+1) % self.MAX_QUEUE self.count -=1 return item else: raise IndexError("The queue is empty.")
def peek(self): if not self.is_empty(): item = self.items[self.front] return item else: raise IndexError("The queue is empty.") def __str__(self): my_list = [] for i in self.items[self.front:]: my_list.append(i) for i in self.items[:self.back+1]: my_list.append(i) return str(my_list)
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
