Class XII Subject: Computer Science Topic: Data Structure in Python (Stack) Marks: 3
Data structure-based question
1 You have a stack named BooksStack that contains records of books. Each book record is 3
represented as a list containing book_title, author_name, and publication_year.
Write the following user-defined functions in Python to perform the specified operations
on the stack BooksStack:
push_book(BooksStack, new_book): This function takes the stack BooksStack and a new
book record new_book as arguments and pushes the new book record onto the stack.
pop_book(BooksStack): This function pops the topmost book record from the stack and
returns it. If the stack is already empty, the function should display "Underflow".
peep(BookStack): This function displays the topmost element of the stack without
deleting it. If the stack is empty, the function should display 'None'.
OR
Write the definition of a user-defined function `push_even(N)` which accepts a list of
integers in a parameter `N` and pushes all those integers which are even from the list `N`
into a Stack named `EvenNumbers`.
Write function pop_even() to pop the topmost number from the stack and returns it. If
the stack is already empty, the function should display "Empty".
Write function Disp_even() to display all element of the stack without deleting them. If
the stack is empty, the function should display 'None'.
For example:
If the integers input into the list `VALUES` are:
[10, 5, 8, 3, 12]
Then the stack `EvenNumbers` should store:
[10, 8, 12]
Answer:
# Initialize the stack
BooksStack = []
# Function to push a new book record
def push_book(BooksStack, new_book):
[Link](new_book)
# Function to pop the topmost book record
def pop_book(BooksStack):
if len(BooksStack) == 0:
print("Underflow")
return None
else:
return [Link]()
# Function to peep at the topmost book record
def peep(BooksStack):
if len(BooksStack) == 0:
print("None")
else:
print("Top Book:", BooksStack[-1])
# Example Usage
push_book(BooksStack, ["The Alchemist", "Paulo Coelho", 1988])
1
Class XII Subject: Computer Science Topic: Data Structure in Python (Stack) Marks: 3
push_book(BooksStack, ["1984", "George Orwell", 1949])
peep(BooksStack)
print("Popped Book:", pop_book(BooksStack))
peep(BooksStack)
Explanation:
• append() is used to push a new element.
• pop() removes and returns the topmost element.
• BooksStack[-1] peeks at the top element without removing it.
2 A list, NList contains following record as list elements: 3
[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.
For example: If the nested list contains the following data:
NList=[["New York", "U.S.A.", 11734], ["Naypyidaw", "Myanmar", 3219],
["Dubai", "UAE", 2194], ["London", "England", 6693], ["Gangtok", "India", 1580],
["Columbo", "Sri Lanka", 3405]]
The stack should contain:
['Naypyidaw', 'Myanmar'],
['Dubai', 'UAE'],
['Columbo', 'Sri Lanka']
The output should be:
['Columbo', 'Sri Lanka']
['Dubai', 'UAE']
['Naypyidaw', 'Myanmar']
Stack Empty
Answer:
# Initialize the stack
travel = []
# Function to push eligible city-country pairs into the stack
def Push_element(NList):
for record in NList:
city, country, distance = record
if country != "India" and distance < 3500:
[Link]([city, country])
2
Class XII Subject: Computer Science Topic: Data Structure in Python (Stack) Marks: 3
# Function to pop elements from the stack and display them
def Pop_element():
if len(travel) == 0:
print("Stack Empty")
else:
while len(travel) > 0:
print([Link]())
print("Stack Empty")
# Example nested list
NList = [
["New York", "U.S.A.", 11734],
["Naypyidaw", "Myanmar", 3219],
["Dubai", "UAE", 2194],
["London", "England", 6693],
["Gangtok", "India", 1580],
["Columbo", "Sri Lanka", 3405]
]
# Push eligible elements into stack
Push_element(NList)
# Pop and display elements
Pop_element()
Explanation:
1. Push_element(NList) iterates through each nested list and pushes
[city, country] to travel only if the country is not India and distance
< 3500 km.
2. Pop_element() pops elements from the stack top to bottom and prints
them. If the stack is empty, it prints "Stack Empty".
3. Stack behavior ensures LIFO order, so the last pushed element is popped
first.
Output for the example:
['Columbo', 'Sri Lanka']
['Dubai', 'UAE']
['Naypyidaw', 'Myanmar']
Stack Empty
3 A list contains following record of a customer: 3
[Customer_name, Phone_number, City]
Write the following user defined functions to perform given operations on the stack
named ‘status’:
(i) Push_element() - To Push an object containing name and Phone number of customers
who live in Goa to the stack
(ii) Pop_element() - To Pop the objects from the stack and display them. Also, display
“Stack Empty” when there are no elements in the stack.
For example:
3
Class XII Subject: Computer Science Topic: Data Structure in Python (Stack) Marks: 3
If the lists of customer details are:
[“Gurdas”, “99999999999”,”Goa”]
[“Julee”, “8888888888”,”Mumbai”]
[“Murugan”,”77777777777”,”Cochin”]
[“Ashmit”, “1010101010”,”Goa”]
The stack should contain
[“Ashmit”,”1010101010”]
[“Gurdas”,”9999999999”]
The output should be:
[“Ashmit”,”1010101010”]
[“Gurdas”,”9999999999”]
Stack Empty
OR
Write a function in Python, Push(SItem) where , SItem is a dictionary containing the
details of stationary items– {Sname:price}.
The function should push the names of those items in the stack who have price greater
than 75. Also display the count of elements pushed into the stack.
For example:
If the dictionary contains the following data:
Ditem={"Pen":106,"Pencil":59,"Notebook":80,"Eraser":25}
The stack should contain
Notebook
Pen
The output should be:
The count of elements in the stack is 2
Here’s a complete Python solution for both versions of your stack problem:
Version 1: Customer stack for Goa
# Initialize the stack
status = []
# Function to push eligible customers from Goa into the stack
def Push_element(customers):
for customer in customers:
name, phone, city = customer
if city == "Goa":
[Link]([name, phone])
# Function to pop elements from the stack and display them
def Pop_element():
if len(status) == 0:
print("Stack Empty")
else:
while len(status) > 0:
print([Link]())
print("Stack Empty")
# Example list of customers
4
Class XII Subject: Computer Science Topic: Data Structure in Python (Stack) Marks: 3
customers = [
["Gurdas", "9999999999", "Goa"],
["Julee", "8888888888", "Mumbai"],
["Murugan", "7777777777", "Cochin"],
["Ashmit", "1010101010", "Goa"]
]
# Push and Pop operations
Push_element(customers)
Pop_element()
Output:
['Ashmit', '1010101010']
['Gurdas', '9999999999']
Stack Empty
Version 2: Stationary items stack
# Initialize the stack
stack_items = []
# Function to push items with price > 75 into the stack
def Push(SItem):
count = 0
for item, price in [Link]():
if price > 75:
stack_items.append(item)
count += 1
print("The count of elements in the stack is", count)
# Example dictionary of items
Ditem = {"Pen":106, "Pencil":59, "Notebook":80, "Eraser":25}
# Push operation
Push(Ditem)
# Display stack
print("Stack contains:")
for item in reversed(stack_items):
print(item)
Output:
The count of elements in the stack is 2
Stack contains:
Notebook
Pen
Explanation
• Stack behavior (LIFO): Last pushed element is popped/displayed first.
• Version 1: Filters customers by City == "Goa".
• Version 2: Pushes only items with price > 75 and counts them.
• reversed(stack_items) is used to display stack from top to bottom
without popping.
5
Class XII Subject: Computer Science Topic: Data Structure in Python (Stack) Marks: 3
4 A stack, named ClrStack, contains records of some colors. Each record is represented as 3
a tuple containing four elements –
ColorName , RED , GREEN , BLUE . ColorName is a string, and RED, GREEN, BLUE are
integers.
For example, a record in the
stack may be ( ' Yellow ' , 237 , 250 , 68)
Write the following user-defined functions in Python to perform the specified operations
on ClrStack :
push_Clr (ClrStack , new_Clr ) : This function takes the stack ClrStack and a new record
new_Clr as arguments and pushes this new record onto the stack.
pop_Clr (ClrStack ) : This function pops the topmost record from the stack and returns it.
Ifthe stack is already empty, the function should display the message "Underf low".
isEmpty (ClrStack ) : This function checks whether the stack is empty. If the stack is
empty, the function should return True, otherwise the function should return False.
OR
Write the following user-defined functions in Python:
1) push_trail(N ,myStack):Here N and mystack are lists, and myStack represents a
stack. The function should push the last 5 elements from the list N onto the stack
myStack. For example, if the list N is [1,2 ,3 ,4 ,5 ,6 ,7 ] , then the function push_trail
()should push the elements 3,4,5,6,7 onto the stack. Therefore the value of stack will
be [3, 4 , 5, 6 , 7] .
Assume that N contains at least 5 elements.
2) pop_one(myStack): The function should pop an element from the stack myStack,
and return this element. If the stack is empty, then the function should display the
message 'Stack Underflow', and return None.
3) display_all(myStack): The function should display all the elements of the stack
myStack, without deleting them. If the stack is empty, the function should display
the message 'Empty Stack'.
Here’s a clean Python solution for both versions of your stack problem. I’ll start
with ClrStack (colors) and then provide push_trail version.
Version 1: ClrStack (Color Records)
# Initialize the stack
ClrStack = []
# Function to push a new color record onto the stack
def push_Clr(ClrStack, new_Clr):
[Link](new_Clr)
# Function to pop the topmost color record
def pop_Clr(ClrStack):
if len(ClrStack) == 0:
print("Underflow")
return None
else:
6
Class XII Subject: Computer Science Topic: Data Structure in Python (Stack) Marks: 3
return [Link]()
# Function to check if the stack is empty
def isEmpty(ClrStack):
return len(ClrStack) == 0
# Example usage
push_Clr(ClrStack, ('Yellow', 237, 250, 68))
push_Clr(ClrStack, ('Red', 255, 0, 0))
print("Top Popped Record:", pop_Clr(ClrStack))
print("Is stack empty?", isEmpty(ClrStack))
print("Top Popped Record:", pop_Clr(ClrStack))
print("Is stack empty?", isEmpty(ClrStack))
Explanation:
• append() pushes a new record.
• pop() removes and returns the topmost record.
• isEmpty() returns True if the stack is empty, otherwise False.
Version 2: push_trail stack operations
# Initialize the stack
myStack = []
# Function to push the last 5 elements of list N onto myStack
def push_trail(N, myStack):
for element in N[-5:]: # last 5 elements
[Link](element)
# Function to pop the topmost element
def pop_one(myStack):
if len(myStack) == 0:
print("Stack Underflow")
return None
else:
return [Link]()
# Function to display all elements without deleting them
def display_all(myStack):
if len(myStack) == 0:
print("Empty Stack")
else:
print("Stack elements (top to bottom):")
for elem in reversed(myStack):
print(elem)
# Example usage
N = [1, 2, 3, 4, 5, 6, 7]
push_trail(N, myStack)
display_all(myStack)
print("Popped Element:", pop_one(myStack))
display_all(myStack)
Explanation:
• N[-5:] slices the last 5 elements of the list.
7
Class XII Subject: Computer Science Topic: Data Structure in Python (Stack) Marks: 3
• reversed(myStack) prints stack from top to bottom without popping.
• pop_one() handles underflow properly.
5 Consider a list named Nums which contains random integers. Write the following user 3
defined functions in Python and perform the specified operations on a stack named
BigNums.
(i) PushBig(): It checks every number from the list Nums and pushes all such numbers
which have 5 or more digits into the stack, BigNums.
(ii) PopBig(): It pops the numbers from the stack, BigNums and displays them. The
function should also display "Stack Empty" when there are no more numbers left in the
stack.
For example:
If the list Nums contains the following data:
Nums = [213,10025,167,254923,14,1297653,31498,386,92765]
Then on execution of PushBig(), the stack BigNums should store :
[10025, 254923, 1297653, 31498, 92765]
And on execution of PopBig(), the following output should be displayed :
92765
31498
1297653
254923
10025
Stack Empty
Here’s a Python solution for the BigNums stack problem using the required user-
defined functions:
# Initialize the stack
BigNums = []
# Function to push numbers with 5 or more digits into BigNums
def PushBig(Nums):
for num in Nums:
if len(str(abs(num))) >= 5: # Check if number has 5 or
more digits
[Link](num)
# Function to pop numbers from BigNums and display them
def PopBig():
if len(BigNums) == 0:
print("Stack Empty")
else:
while len(BigNums) > 0:
print([Link]())
print("Stack Empty")
# Example list
Nums = [213, 10025, 167, 254923, 14, 1297653, 31498, 386, 92765]
# Push numbers with 5 or more digits
PushBig(Nums)
8
Class XII Subject: Computer Science Topic: Data Structure in Python (Stack) Marks: 3
# Pop and display numbers from the stack
PopBig()
Explanation:
1. PushBig():
o Iterates through Nums.
o Converts each number to string and checks len(str(abs(num)))
>= 5 to include numbers with 5 or more digits.
o Pushes eligible numbers onto BigNums using append().
2. PopBig():
o Pops elements from BigNums using pop() (LIFO order).
o Prints "Stack Empty" if the stack is empty.
Output for the example:
92765
31498
1297653
254923
10025
Stack Empty
6 A dictionary, d_city contains the records in the following format: 3
{state:city}
Define the following functions with the given specifications:
(i) push_city(d_city): It takes the dictionary as an argument and pushes all the cities in
the stack CITY whose states are of more than 4 characters.
(ii) pop_city(): This function pops the cities and displays "Stack empty" when there are
no more cities in the stack.
Here’s a clean Python solution for the problem using a stack named CITY:
# Initialize the stack
CITY = []
# Function to push cities whose state name has more than 4
characters
def push_city(d_city):
for state, city in d_city.items():
if len(state) > 4:
[Link](city)
# Function to pop cities from the stack and display them
def pop_city():
if len(CITY) == 0:
print("Stack empty")
else:
while len(CITY) > 0:
print([Link]())
print("Stack empty")
# Example dictionary
d_city = {
"Goa": "Panaji",
9
Class XII Subject: Computer Science Topic: Data Structure in Python (Stack) Marks: 3
"Maharashtra": "Mumbai",
"Kerala": "Thiruvananthapuram",
"Delhi": "New Delhi",
"Karnataka": "Bengaluru"
}
# Push cities with states of more than 4 characters
push_city(d_city)
# Pop and display cities
pop_city()
Explanation:
1. push_city(d_city):
o Iterates through each key-value pair (state: city).
o Checks if the state name length > 4.
o Pushes the corresponding city onto CITY using append().
2. pop_city():
o Pops cities from CITY in LIFO order.
o Prints "Stack empty" if the stack is empty.
Output for the example dictionary:
Bengaluru
Thiruvananthapuram
Mumbai
Stack empty
7 A list contains following record of customer: 3
[Customer_name, Room Type]
Write the following ueer defined functions to perform given operations on the stack
named ‘Hotel':
Push_Cust ( ) - To Push customers' names of those customers who are staying in 'Delux'
Room Type.
Pop_Cust () - To Pop the names of customers from the stack and display them. Also,
display "Underflow" when there are no customers in the stack.
For example:
If the lists with customer details are as follows:
["Siddarth", "Delux"]
["Rahul", "Standard"]
["Jerry", "Delux"]
The stack should contain
Jerry Siddharth
The output should be:
Jerry Siddharth Underflow
OR
Write a function in Python, Push (Vehicle) where, Vehicle is a dictionary containing
details of vehicles - {Car_Name: Maker}.
The function should push the name of car manufactured by 'TATA' (including all the
possible cues like Tata, TaTa, etc.) to the stack.
For example:
10
Class XII Subject: Computer Science Topic: Data Structure in Python (Stack) Marks: 3
If the dictionary contains the following data:
Vehicle={"Santro":"Hyundai","Nexon":"TATA","Safari":"Tata"}
The stack should contain
Safari Nexon
Here’s a Python solution for both versions of your stack problem:
Version 1: Hotel stack for ‘Delux’ customers
# Initialize the stack
Hotel = []
# Function to push customers staying in 'Delux' rooms
def Push_Cust(customers):
for record in customers:
name, room_type = record
if room_type.lower() == "delux": # Case-insensitive check
[Link](name)
# Function to pop customers and display names
def Pop_Cust():
if len(Hotel) == 0:
print("Underflow")
else:
while len(Hotel) > 0:
print([Link](), end=" ")
print("Underflow")
# Example list of customer details
customers = [
["Siddarth", "Delux"],
["Rahul", "Standard"],
["Jerry", "Delux"]
]
# Push and Pop operations
Push_Cust(customers)
Pop_Cust()
Output:
Jerry Siddarth Underflow
Version 2: Vehicle stack for TATA cars
# Initialize the stack
TataCars = []
# Function to push cars manufactured by TATA
def Push(Vehicle):
for car, maker in [Link]():
if [Link]() == "tata": # Case-insensitive match
[Link](car)
# Function to display stack (optional)
def Display_Stack(stack):
11
Class XII Subject: Computer Science Topic: Data Structure in Python (Stack) Marks: 3
if len(stack) == 0:
print("Empty Stack")
else:
for car in reversed(stack): # Display from top to bottom
print(car)
# Example dictionary of vehicles
Vehicle = {"Santro":"Hyundai", "Nexon":"TATA", "Safari":"Tata"}
# Push operation
Push(Vehicle)
# Display stack
Display_Stack(TataCars)
Output:
Safari
Nexon
Explanation
• Stack behavior (LIFO): Last pushed element is popped first.
• Case-insensitive check ensures variants like "TATA" or "Tata" are
considered.
• Push_Cust and Push filter the elements based on a condition before
pushing to the stack.
• Pop_Cust prints all elements and ends with "Underflow" if the stack
becomes empty.
8 A list contains following record of course details for a University: [Course_name, Fees,
Duration]
Write the following user defined functions to perform given operations on the stack
named 'Univ' :
(i) Push_element() - To push an object containing the Course_name, Fees and Duration
of a course, which has fees greater than 100000 to the stack.
(ii) Pop_element() - To pop the object from the stack and display it. Also, display
"Underflow" when there is no element in the stack.
For example:
If the lists of courses details are:
["MCA",200000,3] ["MBA",500000,2] ["BA",100000,3]
The stack should contain: ["MBA",500000,2] ["MCA",200000,3]
Here’s a Python solution for the University course stack problem:
# Initialize the stack
Univ = []
# Function to push courses with fees greater than 100000
def Push_element(courses):
for course in courses:
course_name, fees, duration = course
12
Class XII Subject: Computer Science Topic: Data Structure in Python (Stack) Marks: 3
if fees > 100000:
[Link](course)
# Function to pop courses from the stack and display them
def Pop_element():
if len(Univ) == 0:
print("Underflow")
else:
while len(Univ) > 0:
print([Link]())
print("Underflow")
# Example list of course details
courses = [
["MCA", 200000, 3],
["MBA", 500000, 2],
["BA", 100000, 3]
]
# Push courses with fees > 100000
Push_element(courses)
# Pop and display courses
Pop_element()
Explanation:
1. Push_element(courses):
o Iterates through each course record.
o Checks if fees > 100000.
o Pushes eligible course records onto the stack Univ using append().
2. Pop_element():
o Pops elements from the stack top to bottom using pop().
o Prints "Underflow" if the stack becomes empty.
Output for the example:
['MBA', 500000, 2]
['MCA', 200000, 3]
Underflow
This maintains LIFO (Last-In-First-Out) order, so the last pushed course (MBA)
is popped first.
13