#------------------------------------------------------------------------------ # stack.py # Definition of the Stack class. #------------------------------------------------------------------------------ class Stack(object): """Stack class implementing a LIFO sequence type.""" def __init__(self): """Initialize a Stack object.""" self._list = [] # end def __str__(self): """Return a string representation of self.""" return str(self._list) # end def __repr__(self): """Return a detailed string representation of self.""" return repr(self._list) # end def __len__(self): """Return the length of self.""" return len(self._list) # end def isEmpty(self): """Return true iff self is empty, False otherwise.""" return (len(self)==0) # end def push(self, x): """Add new item x to top of Stack.""" self._list.append(x) # end def pop(self): """Delete and return top item, or Raise IndexError if empty.""" if self.isEmpty(): raise IndexError('pop() called on empty Stack') else: return self._list.pop() # end # end def peek(self): """Return (only) top item, or raise IndexError if empty.""" if self.isEmpty(): raise IndexError('peek() called on empty Stack') else: return self._list[-1] # end # end # end #------------------------------------------------------------------------------ # Test the Stack type #------------------------------------------------------------------------------ def main(): S = Stack() # print(S.pop()) S.push('a') S.push('b') S.push('c') print(S.isEmpty()) print(len(S)) print(S.peek()) print(S.pop()) print(S.pop()) print(S.pop()) print(S.isEmpty()) # S.pop() # S.peek() # end #------------------------------------------------------------------------------ if __name__=='__main__': main() # end