Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Stack:
- def __init__(self):
- self.stack = []
- def push(self, item):
- # Add the item to the top of the stack
- self.stack.append(item)
- def pop(self):
- # Remove and return the topmost item from the stack
- if not self.isEmpty():
- return self.stack.pop(len(self.stack) - 1)
- else:
- print("Error: Stack is empty.")
- return None
- def peek(self):
- # Return the topmost item from the stack without removing it
- if not self.isEmpty():
- return self.stack[len(self.stack) - 1]
- else:
- print("Error: Stack is empty.")
- return None
- def isEmpty(self):
- # Check if the stack is empty
- return len(self.stack) == 0
- # Example usage:
- stack = Stack()
- stack.push(5)
- stack.push(10)
- stack.push(15)
- print("Peek:", stack.peek()) # Output: Peek: 15
- print("Pop:", stack.pop()) # Output: Pop: 15
- print("Peek:", stack.peek()) # Output: Peek: 10
- print("Is Empty:", stack.isEmpty()) # Output: Is Empty: False
- stack.pop()
- stack.pop()
- stack.pop() # Output: Error: Stack is empty.
Advertisement
Add Comment
Please, Sign In to add comment