Data Structure questions
Sno Question
1 Write the definition of a user-defined function `push_even4(N)` which accepts a
list of integers in a parameter `N` and pushes all those integers which are 4 digit
even numbers 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 elements 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:
[1014,2315,3458,1 344, 1213]
Then the stack `EvenNumbers` should store:
[1014,3458,1 344]
Solution:
EvenNumbers=[]
values=[1014,2315,3458,1 344, 1213]
def push_even4(N):
for i in N:
if i>=1000 and i<=9999 and i%2==0:
[Link](i)
def pop_even():
if EvenNumbers==[]:
print("Empty")
else:
return [Link]()
def Disp_even():
if EvenNumbers==[]:
print("None")
else:
for i in EvenNumbers:
print(i)
push_even4(VALUES)
print("Deleted Element:",pop_even())
print("Stack :")
Disp_even()
2 A list contains following record of a customer: [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 Chennai 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:
If the lists of customer details are:
["Ravi", "9876543210", "Chennai"],
["Asha", "9876501234", "Delhi"],
["Kumar", "9123456780", "Chennai"],
["John", "9988776655", "Mumbai"]
The stack should contain
[Ravi", "9876543210]
["Kumar", "9123456780"]
Solution:
customer = [
["Ravi", "9876543210", "Chennai"],
["Asha", "9876501234", "Delhi"],
["Kumar", "9123456780", "Chennai"],
["John", "9988776655", "Mumbai"]
]
status = []
def Push_element():
for i in customer:
if i[2] == "Chennai":
rec = [i[0], i[1]]
[Link](rec)
def Pop_element():
if status == []:
print("Stack Empty")
else:
while status != []:
print([Link]())
# Function Calls
Push_element()
Pop_element()
3 Vedika has created a dictionary containing names and marks as key-value pairs of 5
students. Write a program, with separate user-defined functions to perform the
following operations:
Push the keys (name of the student) of the dictionary into a stack, where the
corresponding value (marks) is greater than 70. Pop and display the content of the
stack.
The dictionary should be as follows:
d={“Ramesh”:58, “Umesh”:78, “Vishal”:90, “Khushi”:60, “Ishika”:95}
The Stack should contain: [“Umesh”, “Vishal”, “Ishika”]
Solution:
d={"Ramesh":58, "Umesh":78, "Vishal":90, "Khushi":60, "Ishika":95}
stack=[]
def Push_element():
for i in d:
if d[i] > 70:
[Link](i)
def Pop_element():
if stack==[]:
print("Stack Empty")
else:
while stack!=[]:
print([Link]())
# Function Calls
Push_element()
print("Stack Elements:")
print(stack)
print("Popped Elements:")
Pop_element()
4 You have a stack named OrderStack that contains order records. Each order record
is represented as a list containing order_id, customer_name, and order_date.
Write the following user-defined functions in Python to perform the specified
operations on the stack OrderStack:
• push_order(OrderStack, new_order): This function takes the stack
OrderStack and a new order record new_order as arguments. It only adds the order
to the stack if the order ID is greater than 1000.
• pop_order(OrderStack): This function pops the topmost order record from
the stack and returns it. If the stack is already empty, the function should display
"Underflow".
• peek_order(OrderStack): This function displays the topmost element of the
stack without deleting it. If the stack is empty, the function should display 'None'.
Solution:
def push_order(OrderStack, new_order):
order_id = new_order[0]
if order_id > 1000:
[Link](new_order)
def pop_order(OrderStack):
if len(OrderStack) == 0:
print("Underflow")
return None
else:
return [Link]()
def peek_order(OrderStack):
if len(OrderStack) == 0:
print("None")
else:
top_element = OrderStack[-1]
print("Topmost Order:", top_element)
5 Consider a list named Nums which contains random integers. Write the following
user 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 [Link]
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
Solution
BigNums = []
Nums = [213, 10025, 167, 254923, 14, 1297653, 31498, 386, 92765]
def PushBig():
for x in Nums:
if N >= 10000:
[Link](x)
def PopBig():
while len(BigNums) > 0:
val = [Link]()
print(val)
else:
print("Stack Empty")
PushBig()
PopBig()
6 Write the following user defined functions:
1. pushEven(N) - This function accepts a list of integers named N as parameter.
It then pushes only even numbers into the stack named EVEN.
2. popEven(EVEN) - This function pops each integer from the stack EVEN
and displays the popped value. When the stack is empty, the message "Stack
Empty" is displayed.
For example: If the list N contains: [10, 5, 3, 8, 15, 4] Then the stack, EVEN
should store:
[10, 8, 4]
Solution
EVEN = []
N = [10, 5, 3, 8, 15, 4]
def pushEven(N):
for num in N:
if num % 2 == 0:
[Link](num)
def popEven(EVEN):
while len(EVEN) > 0:
val = [Link]()
print(val)
else:
print("Stack Empty")
pushEven(N)
popEven(EVEN)
7 A dictionary containing records of stationary items as
Sitem={“Eraser”:25,”Note Book”:125,”Pencil”:50,”Pen”:250}
Write the following user defined functions to perform operations on a stack named
stackitem to
1. Push_Item() – To push the names of those items in the stack who have price
greater than 100. Also display the count of elements pushed into the stack.
2. Pop_Item() – to pop the items from the stack and display them. Also, display
‘Stack Empty’ when there are no elements in the stack.
Solution:
Sitem = {"Eraser": 25, "Note Book": 125, "Pencil": 50, "Pen": 250}
stackitem = []
def Push_Item():
count = 0
for item, price in [Link]():
if price > 100:
[Link](item)
count += 1
print("Total elements pushed:", count)
def Pop_Item():
if len(stackitem) == 0:
print("Stack Empty")
else:
while len(stackitem) > 0:
popped_item = [Link]()
print(popped_item)
print("--- Pushing Elements ---")
Push_Item()
print("\n--- Popping Elements ---")
Pop_Item()
8 A) A list, items contain the following record as list elements [itemno, itemname,
stock].
Each of these records are nested to form a nested list.
Write the following user defined functions to perform the following on a stack
reorder .
i. Push(items)- it takes the nested list as its argument and pushes a list object
containing itemno and itemname where stock is less than 10
3
7
ii. Popitems() -It pops the objects one by one from the stack reorder and also
displays a message ‘Stack empty’ at the end.
items=[[101,'abc',8],[102,'gg',12],[103,'tt',5],[104,'yy',15]]
reorder=[]
def Push(items):
for i in items:
if i[2]<10:
[Link]([i[0],i[1]])
Push(items)
def Popitems():
while len(reorder):
print([Link]())
else:
print("Stack empty")
Popitems()
9 Write a function RShift(Arr) in Python, which accepts a list Arr of numbers and
places all even elements of the list shifted to left.
Sample Input Data of the list Arr= [10,21,30,45,12,11],
Output Arr = [10, 30, 12, 21, 45, 11]
Solution
Arr = [10, 30, 12, 21, 45, 11]
def RShift(Arr):
even_lst = []
odd_lst = []
for x in Arr:
if x % 2 == 0:
even_lst.append(x)
else:
odd_lst.append(x)
Arr[:] = even_lst + odd_lst
10 Consider a dictionary named Books which contains name of books as key and
price as value.
Write the following user defined functions in python and perform the specified
operations on a stack named Book_Name.
I. Push_BName() : It checks price of the book from the dictionary Books
and pushes name of such books which have price more than 350 rupees,
into the stack, Book_Name.
II. Pop_BName(): It deletes the name of books from stack Book_Name and
displays them. The function should also display “Stack is Empty” message
when there is no more book left in the stack.
For example: If the dictionary Books contains the following data:
Books={“Physics”:550,“Maths”:300,“Chem”:480,“Hindi”:250,“CS”:360,“English”
:310}
After execution of Push_BName(), the stack Book_Name should have:
[“Physics”,“Chem”,“CS”]
and on execution of Pop_BName(), the following output should be
displayed:
CS
Chem
Physics
Stack is Empty
Solution:
Books = {"Physics": 550, "Maths": 300, "Chem": 480, "Hindi": 250, "CS": 360,
"English": 310}
Book_Name = []
def Push_BName():
for key, value in [Link]():
if value > 350:
Book_Name.append(key)
def Pop_BName():
if len(Book_Name) == 0:
print("Stack is Empty")
else:
while len(Book_Name) > 0:
popped_book = Book_Name.pop()
print(popped_book)
else:
print("Stack is Empty")
Push_BName()
Pop_BName()
11 A stack, named ClrStack, contains records of some colors. Each record is
represented as 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 userdefined
functions in Python to perform the specified operations on ClrStack:
(i) 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.
(ii) pop_Clr (ClrStack): This function pops the topmost record from the stack and
returns it. If the stack is already empty, the function should display the message
"Underflow".
(iii) 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.
Solution:
ClrStack=[]
def push_Clr(ClrStack):
cname=input("Enter Color Name: ")
r=int(input("Enter RED value: "))
g=int(input("Enter GREEN value: "))
b=int(input("Enter BLUE value: "))
new_Clr=(cname,r,g,b)
[Link](new_Clr)
def pop_Clr(ClrStack):
if ClrStack==[]:
print("Underflow")
else:
return [Link]()
def isEmpty(ClrStack):
if ClrStack==[]:
return True
else:
return False
push_Clr(ClrStack)
print(pop_Clr(ClrStack))
print(isEmpty(ClrStack))
12 A list contains following record of course details for a University: [Course_name,
Fees, Duration]
Course=[["MCA", 200000, 3] , ["MBA", 500000, 2] , ["BA", 100000, 3] ]
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.
The stack should contain
["MBA", 500000, 2]
["MCA", 200000, 3]
(ii) Pop_element( ) - To pop the object from the stack and display it. Also, display
“Underflow”
when there is no element in the stack.
Solution
Course=[["MCA",200000,3],
["MBA",500000,2],
["BA",100000,3]]
Univ=[]
def Push_element():
for i in Course:
if i[1] > 100000:
[Link](i)
def Pop_element():
if Univ==[]:
print("Underflow")
else:
print([Link]())
Push_element()
print("Popped Element:")
Pop_element()
13 A company having various departments and Number of computers (PC) are stored as key-value pairs
in a dictionary as given below:
SETUP={"HR":10,"QUALITY":25,"SUPPORT":50,"PRODUCTION":20,"SUPPLY":25}
Write user defined functions to perform the following operations:
I Push the keys (name of the department) of the dictionary into a stack named DEPT, where
the corresponding value (Number of PC) is 25 or more.
I Pop and display the content of the stack. Also ,display “Stack Empty” when there are no
elements in the stack.
The output from the program should be
SUPPLY
SUPPORT
QUALITY
stack Empty
14 A stack named BookStack stores book records. Each record is a List containing
three elements – [BookTitle, Author, Price]. Example record: ['Python Basics',
'Guido', 499]
Write the following user-defined Python functions to perform stack operations on
BookStack:
1. push_Book(BookStack, new_Book): This function receives the stack
BookStack and a new record new_Book as arguments and pushes the new record
onto the stack.
2. pop_Book(BookStack): This function pops and returns the topmost book
record from the [Link] the stack is empty, it should display "Underflow - No book
to remove".
Solution
BookStack=[]
def push_Book(BookStack, new_Book):
[Link](new_Book)
def pop_Book(BookStack):
if BookStack==[]:
print("Underflow - No book to remove")
else:
return [Link]()
# Main Program
b1=['Python Basics', 'Guido', 499]
push_Book(BookStack,b1)
print("Stack Elements:")
print(BookStack)
print("Deleted Record:")
print(pop_Book(BookStack))
15 Write user-defined functions Push_VowelWord(Stk, Sentence) and
Pop_VowelWord(Stk) in Python:
Push_VowelWord(Stk, Sentence) splits the string Sentence into individual
words and pushes only those words that start with a vowel (A, E, I, O, U)
into Stk. The validation must be completely case-insensitive.
Pop_VowelWord(Stk) pops all elements from the stack one by one and
returns them as a combined space-separated string output string.