Group_Coder

Implement a Stack using a Python list (built-in methods are not allowed)

Jul 24th, 2023
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. class Stack:
  2. def __init__(self):
  3. self.stack = []
  4.  
  5. def push(self, item):
  6. # Add the item to the top of the stack
  7. self.stack.append(item)
  8.  
  9. def pop(self):
  10. # Remove and return the topmost item from the stack
  11. if not self.isEmpty():
  12. return self.stack.pop(len(self.stack) - 1)
  13. else:
  14. print("Error: Stack is empty.")
  15. return None
  16.  
  17. def peek(self):
  18. # Return the topmost item from the stack without removing it
  19. if not self.isEmpty():
  20. return self.stack[len(self.stack) - 1]
  21. else:
  22. print("Error: Stack is empty.")
  23. return None
  24.  
  25. def isEmpty(self):
  26. # Check if the stack is empty
  27. return len(self.stack) == 0
  28.  
  29. # Example usage:
  30. stack = Stack()
  31. stack.push(5)
  32. stack.push(10)
  33. stack.push(15)
  34.  
  35. print("Peek:", stack.peek()) # Output: Peek: 15
  36. print("Pop:", stack.pop()) # Output: Pop: 15
  37. print("Peek:", stack.peek()) # Output: Peek: 10
  38. print("Is Empty:", stack.isEmpty()) # Output: Is Empty: False
  39.  
  40. stack.pop()
  41. stack.pop()
  42. stack.pop() # Output: Error: Stack is empty.
  43.  
Advertisement
Add Comment
Please, Sign In to add comment