[go: up one dir, main page]

0% found this document useful (0 votes)
5 views4 pages

Stack Basic

The document describes a Python class for implementing basic stack operations, including methods for checking if the stack is empty, pushing and popping items, peeking at the top element, checking the size, and displaying the stack contents. It includes example usage of the stack class, demonstrating its functionality. The output shows the results of various stack operations performed in sequence.

Uploaded by

ahalya704
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views4 pages

Stack Basic

The document describes a Python class for implementing basic stack operations, including methods for checking if the stack is empty, pushing and popping items, peeking at the top element, checking the size, and displaying the stack contents. It includes example usage of the stack class, demonstrating its functionality. The output shows the results of various stack operations performed in sequence.

Uploaded by

ahalya704
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Stack Basic Operations Using Python

class Stack:
def __init__(self):
self.stack = []

def is_empty(self):
return len(self.stack) == 0

def push(self, item):


self.stack.append(item)
print(f"Pushed: {item}")

def pop(self):
if self.is_empty():
return "Stack is empty"
return f"Popped: {self.stack.pop()}"

def peek(self):
if self.is_empty():
return "Stack is empty"
return f"Top element: {self.stack[-1]}"
def size(self):
return f"Stack size: {len(self.stack)}"

def display(self):
return f"Stack: {self.stack}"

program starts here


s = Stack()
print(s.is_empty()) #?
s.push(10)
s.push(20)
s.push(30)
print(s.display()) # Stack: [?]
print(s.peek()) # Top element: ?
print(s.pop()) # Popped: ?
print(s.display()) # Stack: [?]
print(s.size()) # Stack size: ?
print(s.is_empty()) #?
OUTPUT

True
Pushed: 10
Pushed: 20
Pushed: 30
Stack: [10, 20, 30]
Top element: 30
Popped: 30
Stack: [10, 20]
Stack size: 2
False

You might also like