Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

A \"Stack\" is an abstract data type for storing a collection of items, where it

ID: 3745208 • Letter: A

Question

A "Stack" is an abstract data type for storing a collection of items, where items are both added and removed from one end of the collection. The methods for adding and removing items from a stack are traditionally called "push(" and "pop()" respectively. A method called "peek()" returns the value on the top of the stack, but does not remove it from the stack. A "size()" method returns the number of items on the stack, and a method "is_empty()" returns a boolean indicating if the stack is empty Complete and test the Stack implementations. Exceptions are raised when preconditions are violated. For example, an IndexError will be raised if a client program attempt to pop from an empty stack. You should modify the pop(/peek() method of the Stack class to raise an IndexError if an attempt is made to pop/peek from an empty stack. You should include the entire Stack class definition in your answer to this question For example: Test Result try: The stack is empty! sStack() print (s.pop)) except IndexError as err: print (err) try: The stack is empty! s Stack() print (s.peek()) except IndexError as err: print (err)

Explanation / Answer

class Stack: def __init__(self): self.lst = [] def push(self, item): self.lst.append(item) def pop(self): if self.is_empty(): raise IndexError('The stack is empty!') return self.lst.pop() def peek(self): if self.is_empty(): raise IndexError('The stack is empty!') return self.lst[-1] def size(self): return len(self.lst) def is_empty(self): return self.size() == 0

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote