Exceptions are raised when preconditions are violated. For example, an IndexError will be raised if a program attempts to dequeue from an empty queue. You should modify the dequeue() method and peek() method of the Queue class to raise an IndexError with the message "ERROR: The queue is empty!" if an attempt is made to dequeue from an empty queue or peek into an empty queue.
Submit the entire Queue class definition in your answer to this question.
Test | Result |
---|---|
try: q = Queue() q.enqueue(2) print(q.dequeue()) except IndexError as err: print (err) |
2 |
try: q = Queue() q.enqueue(2) q.enqueue(1) print(q.dequeue()) print(q.dequeue()) print(q.dequeue()) except IndexError as err: print (err) |
2 1 ERROR: The queue is empty! |
try: q = Queue() print(q.peek()) except IndexError as err: print (err) |
ERROR: The queue is empty! |
# Thank you for asking the question.
class Queue:
def __init__(self):
self.elements = []
def enqueue(self, item):
self.elements.insert(0,item)
def dequeue(self):
try:
return self.elements.pop()
except IndexError as err:
return "ERROR:The queue is empty!"
def peek(self):
try:
return self.elements[len(self.elements)-1]
except IndexError as err:
return "ERROR:The queue is empty!"
q=Queue()
q.enqueue(4)
q.enqueue(5)
q.enqueue(6)
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
q.enqueue(10)
print(q.dequeue())
print(q.peek())
# Hope this will help you.
# Feel free to ask any doubt and once again thank you very much.
Get Answers For Free
Most questions answered within 1 hours.