Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create stack.py #434

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions stack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
class Stack:
def __init__(self):
self.items = []

def is_empty(self):
"""Check if the stack is empty."""
return len(self.items) == 0

def push(self, item):
"""Add an item to the top of the stack."""
self.items.append(item)

def pop(self):
"""Remove and return the top item from the stack."""
if not self.is_empty():
return self.items.pop()
else:
raise IndexError("pop from empty stack")

def peek(self):
"""Return the top item from the stack without removing it."""
if not self.is_empty():
return self.items[-1]
else:
raise IndexError("peek from empty stack")

def size(self):
"""Return the number of items in the stack."""
return len(self.items)

# Example usage:
stack = Stack()
stack.push(5)
stack.push(10)
print(f"Top item: {stack.peek()}")
print(f"Stack size: {stack.size()}")
print(f"Popped item: {stack.pop()}")
print(f"Stack size after pop: {stack.size()}")