Implement a simple Stack class in Python
A Stack is a data structure that follows the Last-In-First-Out (LIFO) principle. We can use Python's list to implement a simple Stack class. This class will include the following basic operations:
push(item): Push the elementitemonto the top of the stack.pop(): Remove and return the element at the top of the stack.peek(): Return the element at the top of the stack without removing it.is_empty(): Check whether the stack is empty.size(): Return the number of elements in the stack.
Example
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
if self.is_empty():
raise IndexError("pop from empty stack")
return self.items.pop()
def peek(self):
if self.is_empty():
raise IndexError("peek from empty stack")
return self.items[-1]
def size(self):
return len(self.items)
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
if self.is_empty():
raise IndexError("pop from empty stack")
return self.items.pop()
def peek(self):
if self.is_empty():
raise IndexError("peek from empty stack")
return self.items[-1]
def size(self):
return len(self.items)
Code analysis:
__init__(self): Initialize an empty listitemsto store the elements in the stack.is_empty(self): Check whether the stack is empty; ifitemsthe list is empty, returnTrue, otherwise returnFalse。push(self, item): Add the elementitemto theitemsend of the list, i.e., push it onto the top of the stack.pop(self): Remove and returnitemsthe last element of the list, i.e., the top element of the stack. If the stack is empty, raiseIndexErrorexception.peek(self): Returnitemsthe last element of the list, i.e., the top element of the stack, without removing it. If the stack is empty, raiseIndexErrorexception.size(self): Returnitemsthe length of the list, i.e., the number of elements in the stack.
Output result:
Example
# Example usage
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.peek()) # Output: 3
print(stack.pop()) # Output: 3
print(stack.size()) # Output: 2
print(stack.is_empty()) # Output: False
stack.pop()
stack.pop()
print(stack.is_empty()) # Output: True
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.peek()) # Output: 3
print(stack.pop()) # Output: 3
print(stack.size()) # Output: 2
print(stack.is_empty()) # Output: False
stack.pop()
stack.pop()
print(stack.is_empty()) # Output: True
In this example, we first create a stack objectstack, then push the elements one by one1、2and3onto the stack.3), and remove it. Finally, we check the size of the stack and whether it is empty.
Python3 Examples