Stack Programs in Python - 15 Examples
1. Basic Stack Push & Pop
stack = []
[Link](10)
[Link](20)
[Link](30)
print("Stack after pushes:", stack)
print("Popped:", [Link]())
print("Stack after pop:", stack)
2. Push Palindromes into Stack
stack = []
def is_palindrome(word):
return word == word[::-1]
n = int(input("Enter number of words: "))
for _ in range(n):
word = input("Enter a word: ")
if is_palindrome(word):
[Link](word)
print(f"'{word}' added.")
else:
print(f"'{word}' skipped.")
print("Final Palindrome Stack:", stack)
3. Stack with Underflow & Overflow Check
MAX = 5
stack = []
def push(item):
if len(stack) >= MAX:
print("Overflow! Stack is full.")
else:
[Link](item)
print(f"{item} pushed to stack.")
def pop():
if not stack:
print("Underflow! Stack is empty.")
else:
print(f"Popped: {[Link]()}")
# Example
push(10); push(20); push(30); push(40); push(50); push(60)
pop(); pop(); pop(); pop(); pop(); pop()
4. Reverse a String Using Stack
stack = []
string = input("Enter a string: ")
for ch in string:
[Link](ch)
rev = ""
while stack:
rev += [Link]()
print("Reversed String:", rev)
5. Store Multiples of a Number in a Stack
stack = []
n = int(input("Enter a number: "))
limit = int(input("How many multiples? "))
for i in range(1, limit + 1):
[Link](n * i)
print("Multiples Stack:", stack)
6. Push Only Even Numbers into Stack
stack = []
numbers = list(map(int, input("Enter numbers separated by space: ").split()))
for num in numbers:
if num % 2 == 0:
[Link](num)
print("Even Numbers Stack:", stack)
7. Stack to Check Balanced Parentheses
def is_balanced(expr):
stack = []
for ch in expr:
if ch in "([{":
[Link](ch)
elif ch in ")]}":
if not stack:
return False
if (stack[-1], ch) in [('(', ')'), ('[', ']'), ('{', '}')]:
[Link]()
else:
return False
return not stack
expr = input("Enter expression: ")
print("Balanced" if is_balanced(expr) else "Not Balanced")
8. Stack to Convert Decimal to Binary
stack = []
n = int(input("Enter decimal number: "))
while n > 0:
[Link](n % 2)
n //= 2
binary = ""
while stack:
binary += str([Link]())
print("Binary:", binary)
9. Stack to Reverse a List
stack = []
lst = [1, 2, 3, 4, 5]
for item in lst:
[Link](item)
rev_list = []
while stack:
rev_list.append([Link]())
print("Reversed List:", rev_list)
10. Push Names Starting with 'A'
stack = []
n = int(input("Enter number of names: "))
for _ in range(n):
name = input("Enter name: ")
if [Link]().startswith('a'):
[Link](name)
print("Names Stack:", stack)
11. Push Numbers Greater Than 50
stack = []
nums = [10, 60, 45, 100, 30]
for num in nums:
if num > 50:
[Link](num)
print("Numbers > 50 Stack:", stack)
12. Find Maximum in Stack
stack = [10, 50, 20, 90, 30]
print("Maximum value in stack:", max(stack))
13. Count Elements in Stack
stack = [1, 2, 3, 4, 5]
print("Number of elements in stack:", len(stack))
14. Remove All Elements from Stack
stack = [10, 20, 30, 40]
while stack:
[Link]()
print("Stack after removing all elements:", stack)
15. Stack to Store Factors of a Number
stack = []
n = int(input("Enter a number: "))
for i in range(1, n+1):
if n % i == 0:
[Link](i)
print("Factors Stack:", stack)
# Maximum size of the stack
MAX_SIZE = 5
# Function to push a book onto the stack
def push_book(BooksStack, new_book):
if len(BooksStack) >= MAX_SIZE:
print("Overflow")
else:
[Link](new_book)
print(f"Book '{new_book[0]}' added to the stack.")
# Function to pop a book from the stack
def pop_book(BooksStack):
if len(BooksStack) == 0:
print("Underflow")
return None
else:
removed_book = [Link]()
print(f"Book '{removed_book[0]}' removed from the stack.")
return removed_book
# Function to peep (view) the topmost book in the stack
def peep_book(BooksStack):
if len(BooksStack) == 0:
print("None")
return None
else:
print(f"Top book: {BooksStack[-1]}")
return BooksStack[-1]
# Main Program
BooksStack = []
while True:
print("\n--- Menu ---")
print("1. Push Book")
print("2. Pop Book")
print("3. Peep Book")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
title = input("Enter Book Title: ")
author = input("Enter Author Name: ")
year = input("Enter Publication Year: ")
push_book(BooksStack, [title, author, year])
elif choice == '2':
pop_book(BooksStack)
elif choice == '3':
peep_book(BooksStack)
elif choice == '4':
print("Exiting program...")
break
else:
print("Invalid choice! Please try again.")
A list, NList contains following record as list elements: [City, Country, distance from Delhi]
Each of these records are nested together to form a nested list. Write the following user
defined functions in Python to perform the specified operations on the stack named travel.
(i) Push_element(NList): It takes the nested list as an argument and pushes a list object
containing name of the city and country, which are not in India and distance is less than
3500 km from Delhi. (ii) Pop_element(): It pops the objects from the stack and displays
them. Also, the function should display “Stack Empty” when there are no elements in the
stack.
# Stack initialization
travel = []
# Function to push qualifying cities into the stack
def Push_element(NList):
for record in NList:
city, country, distance = record
if [Link]() != "india" and distance < 3500:
[Link]([city, country])
print("Push operation completed.")
# Function to pop cities from the stack
def Pop_element():
if len(travel) == 0:
print("Stack Empty")
return
while len(travel) > 0:
city, country = [Link]()
print(f"{city}, {country}")
print("Stack Empty")
# Example nested list
NList = [
["Kathmandu", "Nepal", 813],
["Colombo", "Sri Lanka", 2420],
["Paris", "France", 6573],
["Bangkok", "Thailand", 2914],
["Mumbai", "India", 1400]
]
# Main program
Push_element(NList)
Pop_element()
Python function to find all divisors (factors) of a number in descending order using a
stack:
def divisors_desc_stack(n):
stack = []
# Push all divisors into the stack
for i in range(1, n + 1):
if n % i == 0:
[Link](i)
# Pop from stack to get descending order
result = []
while stack:
[Link]([Link]())
return result
# Example usage
num = int(input("Enter a number: "))
print("Divisors in descending order:", divisors_desc_stack(num))
Function to find Fibonacci numbers up to N and store in a stack
def fibonacci_stack(limit):
stack = []
a, b = 0, 1
while a <= limit:
[Link](a)
a, b = b, a + b
return stack
# Example
num = 50
stack = fibonacci_stack(num)
print("Fibonacci numbers:", stack)
Function to store digits of a number in a stack
def digits_stack(n):
stack = []
for digit in str(n):
[Link](int(digit))
return stack
# Example
num = 98765
stack = digits_stack(num)
print("Digits:", stack)
Find vowels in a string and store in a stack
def vowels_stack(s):
stack = []
vowels = "AEIOUaeiou"
for ch in s:
if ch in vowels:
[Link](ch)
return stack
sentence = "Stack in Python is Fun"
print("Vowels:", vowels_stack(sentence))