[docs]classStack:""" A simple stack data structure implementation using the deque from the collections module. Attributes: _stack (collections.deque): The internal deque used to store the stack elements. """def__init__(self,data:Optional[list]=None)->None:""" Initializes the Stack object with the given data (optional). Args: data (Optional[list]): The initial data to be added to the stack. """self._stack=deque(data)ifdataelsedeque()
[docs]defpush(self,item:Any)->None:""" Pushes an item onto the top of the stack. Args: item (Any): The item to be pushed onto the stack. """self._stack.append(item)
[docs]defpop(self)->Any:""" Removes and returns the top item from the stack. Returns: Any: The top item from the stack. Raises: IndexError: If the stack is empty. """ifself.is_empty():raiseIndexError("No items to pop.")returnself._stack.pop()
[docs]deftop(self)->Any:""" Returns the top item from the stack without removing it. Returns: Any: The top item from the stack. Raises: IndexError: If the stack is empty. """ifself.is_empty():raiseIndexError("No items to top.")returnself._stack[-1]
[docs]defis_empty(self)->bool:""" Checks if the stack is empty. Returns: bool: True if the stack is empty, False otherwise. """returnlen(self._stack)==0
def__len__(self)->int:""" Returns the number of items in the stack. Returns: int: The number of items in the stack. """returnlen(self._stack)def__getitem__(self,index:int)->Any:""" Returns the item at the specified index from the top of the stack. Args: index (int): The index of the item to retrieve, where 0 is the top of the stack. Returns: Any: The item at the specified index. Raises: IndexError: If the index is out of range. """ifindex<0orindex>=len(self._stack):raiseIndexError("Index out of range.")returnself._stack[-(index+1)]
[docs]defclear(self)->None:""" Clears all items from the stack. """self._stack.clear()
@propertydefas_list(self)->list:""" Returns the stack as a list, with the top item first. Returns: list: The stack as a list. """returnlist(self._stack)def__iter__(self):""" Returns an iterator over the stack. """returniter(self._stack)