Guest User

Untitled

a guest
May 26th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. def __init__(self):
  2. """Create an empty stack."""
  3. self._data = [] # nonpublic list instance
  4.  
  5. def __len__(self):
  6. """Return the number of elements in the stack."""
  7. return len(self._data)
  8.  
  9. def is_empty(self):
  10. """Return True if the stack is empty."""
  11. return len(self._data) == 0
  12.  
  13. def push(self, e):
  14. """Add element e to the top of the stack."""
  15. self._data.append(e) # new item stored at end of list
  16.  
  17. def top(self):
  18. """Return (but do not remove) the element at the top of the stack. Raise Empty exception if the stack is empty. """
  19. if self.is_empty():
  20. raise Empty('Stack is empty')
  21. return self._data[-1] # the last item in the list
  22.  
  23. def pop(self):
  24. """Remove and return the element from the top of the stack (i.e., LIFO). Raise Empty exception if the stack is empty. """
  25. if self.is_empty():
  26. raise Empty("Stack is empty")
  27. return self._data.pop() # remove last item from list
Add Comment
Please, Sign In to add comment