0% found this document useful (0 votes)
215 views

Chapter 5 Programs

The document provides examples of Python functions to perform operations like push, pop and display contents of a stack. It includes functions to push and pop elements from a list or dictionary onto a stack based on certain criteria like divisibility, range of values etc. and display the results. Detailed explanations and outputs are given for each example function.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
215 views

Chapter 5 Programs

The document provides examples of Python functions to perform operations like push, pop and display contents of a stack. It includes functions to push and pop elements from a list or dictionary onto a stack based on certain criteria like divisibility, range of values etc. and display the results. Detailed explanations and outputs are given for each example function.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

1.

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 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:
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
Ans:
status=[]
def Push_element(cust):
if cust[2]=="Goa":
L1=[cust[0],cust[1]]
status.append(L1)
def Pop_element ():
num=len(status)
while len(status)!=0:
dele=status.pop()
print(dele)
num=num-1
else:
print("Stack Empty")
2. 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
Ans:
stackItem=[]
def Push(SItem):
count=0
for k in SItem:
if (SItem[k]>=75):
stackItem.append(k)
count=count+1
print("The count of elements in the stack is : ", count)
3. Alfred has created a list, L containing marks of 10 students. Write a program,
with separate user defined function to perform the following operation:
PUSH()- Traverse the content of the List,L and push all the odd marks into the
stack,S.
POP()- Pop and display the content of the stack.
Example: If the content of the list is as follows:
L=[87, 98, 65, 21, 54, 78, 59, 64, 32, 49]
Then the output of the code should be: 49 59 21 65 87
Ans:
def PUSH(S):
for i in L:
if i%2! =0:
S.append(i)
return(S)
def POP ():
num=len(S)
while len(S)!=0:
dele=S.pop()
print(dele)
num=num-1
else:
print("empty")
4. Write a function in Python, Push(BItem) where , BItem is a dictionary
containing the details of bakery items– {Bname:price}.
The function should push the names of those items in the stack, S who have
price less than 50.
For example:
If the dictionary contains the following data:
Bitem={"Bread":40,"Cake":250,"Muffins":80,"Biscuits":25}

The stack should contain


Bread
Biscuits
Ans:
def Push(Bitem):
for i,j in Bitem.items():
if j<50:
S.append(i)
5. Write a function in Python PUSH(Arr), where Arr is a list of numbers. From
this list push all numbers divisible by 5 into a stack implemented by using a list.
Display the stack if it has at least one element, otherwise appropriate error
message.

def PUSH(Arr,value):
s=[]
for x in range(0,len(Arr)):
if Arr[x]%5==0:
s.append(Arr[x])
if len(s)==0:
print("Empty Stack")
else:
print(s)
6. Write a function in Python POP(Arr), where Arr is a stack implemented by a list
of numbers. The function returns the value deleted from the stack.
def POP(Arr):
if Arr:
deleted_value=Arr.pop()
return deleted_value
else:
print(“Stack is empty”)
return None
stack=[1,2,3,4,5]
deleted_value=POP(stack)
print(“Deleted value from the stack:”, deleted_value)
print(“Updated stack after deletion:”, stack)
7. Mohammed has created a dictionary containing names and marks of computer
science 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 (CS marks) are more than or equal to 90 .
● Pop and display the content of the stack, if the stack is empty display the
message as “UNDER FLOW”
For example: If the sample content of the dictionary is as follows:
CS={"Raju":80, "Balu":91, "Vishwa":95, "Moni":80, “Govind":90}
The push operatio’s output from the program should be:
Balu Vishwa Govind
The pop operation must display
Govind
Vishwa
Balu
“UNDER FLOW”
ANS:
CS={"Raju":80, "Balu":91, "Vishwa":95, "Moni":80,"Govind":90}
names=[]
def push():
for i in CS: #1/ 2 MARK
if CS[i]>=90: #1/ 2 MARK
names.append(i) #1/ 2 MARK
print(names)
def pop():
while len(names)!=0: #1/ 2 MARK
print(names.pop()) #1/ 2 MARK
else:
print("UNDER FLOW") #1/ 2 MARK
push()
pop()
8. Dev Anand have a list of 10 numbers. You need to help him create a program
with separate user defined functions to perform the following operations based
on this list.
● Traverse the content of the list and push the numbers divisible by 5 into the
stack.
● Pop and display the content of the stack, if the stack is empty display the
message” STACK EMPTY”
For Example:
If the sample Content of the list is as follows:
N=[2,5,10,13,20,23,45,56,60,78]
After the push operation the list must contain
5,10,20,45,60
And pop operation must display the output as
60
45
20
10
5
STACK EMPTY
ANS:
N=[2,5,10,13,20,23,45,56,60,78]
stack=[]
def push():
for i in N: #1/ 2 MARK
if i%5==0: #1/ 2 MARK
stack.append(i) #1/ 2 MARK
print(stack)
def pop():
while len(stack)!=0: #1/ 2 MARK
print(stack.pop()) #1/ 2 MARK
else:
print("STACK EMPTY") #1/ 2 MARK
push()
pop()
9. Thushar received a message(string) that has upper case and lower case
alphabet.He want to extract all the upper case letters separately .Help him to do
his task by performing the following user defined function in Python:
a) Push the upper case alphabets in the string into a STACK
b) Pop and display the content of the stack.
For example:
If the message is “All the Best for your Pre-board Examination”
The output should be: E P B A
ANS:
def push(s,ch):
s.append(ch)
def pop(s):
if s!=[]:
return s.pop()
else:
return None
string=“All the Best for your Pre-board Examination”
st=[]
for ch in string:
if ch.isupper():
push(st,ch)
while True:
item=pop(st)
if item!=None:
print(item,end= ‘ ‘)
else:
break
10. A nested list contains the data of visitors in a museum. Each of the inner lists
contains the following data of a visitor:
[V_no (int), Date (string), Name (string), Gender (String M/F), Age (int)]
Write the following user defined functions to perform given operations on the
stack named "status":
(i) Push_element(Visitors) - To Push an object containing Gender of visitor who
are in the age range of 15 to 20.
(ii) Pop_element() - To Pop the objects from the stack and count and display the
number of Male and Female entries in the stack. Also, display “Done” when
there are no elements in the stack.
For example: If the list of Visitors contains:
[['305', "10/11/2022", “Geeta”,"F”, 35],
['306', "10/11/2022", “Arham”,"M”, 15],
['307', "11/11/2022", “David”,"M”, 18],
['308', "11/11/2022", “Madhuri”,"F”, 17],
['309', "11/11/2022", “Sikandar”,"M”, 13]]
The stack should contain
F
M
M
The output should be:
Female: 1
Male: 2
Done
ANS:
visitors=[['305', '10/11/2022', 'Geeta','F', 15],['306', '10/11/2022', 'Arham','M',
15],\['307', "11/11/2022", 'David','M', 18],['308', "11/11/2022", 'Madhuri','F',
17]]
status=[]
def Push_Element(visitors):
global status
for i in visitors:
if i[4]>=15 and i[4]<=20:
status.append(i[3])
def Pop_Element():
global status
m,f=0,0
if status!=[]:
r=status.pop()
if r== ‘F’:
f+=1
else:
m+=1
else:
print(“Female :”,f)
print(“Male :”,m)
print("Done")
11. Write a function in Python, Push(EventDetails) where , EventDetails is a
dictionary containing the number of persons attending the events– {EventName
: NumberOfPersons}. The function should push the names of those events in the
stack named ‘BigEvents’ which have number of persons greater than 200. Also
display the count of elements pushed on to the stack.
For example:
If the dictionary contains the following data:
EventDetails ={"Marriage":300, "Graduation Party":1500, "Birthday Party":80,
"Get together" :150}
The stack should contain :
Marriage
Graduation Party
The output should be:
The count of elements in the stack is 2
ANS:
def Push(EventDetails):
BigEvents=[]
count=0
for i in EventDetails:
if EventDetails[i]>200:
BigEvents.append(i)
count+=1
print(“The count of elements in the stack is”, count)
12. A list of numbers is used to populate the contents of a stack using a function
push(stack, data) where stack is an empty list and data is the list of numbers.
The function should push all the numbers that are even to the stack.
Also write the function pop(stack) that removes and returns the top element of
the stack on its each call. Also write the function calls.
ANS:
data = [1,2,3,4,5,6,7,8]
stack = []
def push(stack, data):
for x in data:
if x % 2 == 0:
stack.append(x)
def pop(stack):
if len(stack)==0:
return "stack empty"
else:
return stack.pop()
push(stack, data)
print(pop(stack))
13. Write the following user defined functions to perform given operations on the
stack named ‘stud_details’:
(i) Push_element() - To Push an object containing nameand
age of students who live in hostel “Ganga” 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
thestack.
For example:
If the lists of customer detailsare:
[“Barsat”,17,”Ganga”]
[“Ruben”, 16,”Kaveri”]
[“Rupesh”,19,”Yamuna”]
The stack should contain
[“Barsat”,17,”Ganga”]
The output should be:
[“Barsat”,17,”Ganga”]
Stack Empty
ANS:
stud_details=[]
def push_element(lis):
if(lis[2]=="Ganga"):
stud_details.append([lis[0],lis[1]])
def pop_element():
while(len(stud_details)>0):
print(stud_details.pop())
print("Stack Empty")
14. A list named as Record contains following format of for students:
[student_name, class, city].
Write the following user defined functions to perform given operations on the
stack named ‘Record’:
(i) Push_record(Record) – To pass the list Record = [ ['Rahul', 12,'Delhi'],
[‘Kohli',11,'Mumbai'], ['Rohit',12,'Delhi'] ] and then Push an object containing
Student name, Class and City of student belongs to ‘Delhi’ to the stack Record
and display and return the contents of stack
(ii) Pop_record(Record) – To pass following Record [[“Rohit”,”12”,”Delhi”]
[“Rahul”, 12,”Delhi”] ] and then to Pop all the objects from the stack and at last
display “Stack Empty” when there is no student record in the stack. Thus the
output should be: -
[“Rohit”,”12”,”Delhi”]
[“Rahul”, 12,”Delhi”]
Stack Empty
ANS:
def Push_record(): # (1½ mark for correct push element)
for i in List:
if i[2]=="Delhi":
Record.append(i)
print(Record)
def Pop_record(): # (1½ mark for correct push element)
while True:
if len(Record)==0:
print('Empty Stack')
break
else:
print(Record.pop())
Push(Dict_Product)
15. Julie has created a dictionary containing names and marks as key value pairs of
6 students. Write a program, with separate user defined functions to perform the
following operations
(a) Push the keys (name of the student) of the dictionary into a stack, where the
corresponding value (marks) is greater than 75.
(b) Pop and display the content of the stack. For example If the sample content
of the dictionary
is as follows
R={“OM”:76, “JAI”:45, “BOB”:89, “ALI”:65, “ANU”:90, “TOM”:82}
The output from the program should be
TOM ANU BOB OM
_Sol :
R={“OM”:76, “JAI”:45, “BOB”:89, “ALI”: 65, “ANU”:90, “TOM”:82}
def PUSH(S,N):
S.append(N)
def POP(S):
if S!-[]:
return S.pop()
else:
return None
ST=[ ]
for k in R:
if R[k]>=75:
PUSH(ST, k)
while True:
if ST!=[]:
print(POP(ST),end= “ ”)
else:
break
16. Alam has a list containing 10 integers. You need to help him create a program
with separate user defined functions to perform the given operations
based on this list.
(a) Traverse the content of the list and push the even numbers into a stack.
(b) Pop and display the content of the stack.
For example, If the sample content of the list is as follows
N = [12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
Sample Output of the code should be:
38 22 98 56 34 12
_Sol :
N = [12,13,34,56,21,79,98,22,35,38]
def PUSH(S, N):
S.append(N)
def POP(S):
if S!=[]:
return S.pop()
else:
return None
ST=[ ]
for k in N:
if k%2==0:
PUSH(ST,k)
while True:
if ST!=[]:
print(POP(ST),end=“ ”)
else:
break

17. A dictionary contains the names of some cities and their population in crore.
Write a python function push(stack, data), that accepts an empty list, which
is the stack and data, which is the dictionary and pushes the names of those
countries onto the stack whose population is greater than 25 crores.
For example :
The data is having the contents {'India':140, 'USA':50, 'Russia':25, 'Japan':10}
then the execution of the function push() should push India and USA on the
stack.
ANS:
data={'India':140, 'USA':50, 'Russia':25, 'Japan':10}
stack=[]
def push(stack, data):
for x in data:
if data[x]>25:
stack.append(x)
push(stack, data)
print(stack)
18. A list of numbers is used to populate the contents of a stack using a function
push(stack, data) where stack is an empty list and data is the list of numbers.
The function should push all the numbers that are even to the stack. Also
write the function pop(stack) that removes the top element of the stack on
its each call. Also write the function calls.
ANS:
data = [1,2,3,4,5,6,7,8]
stack = []
def push(stack, data):
for x in data:
if x % 2 == 0:
stack.append(x)
def pop(stack):
if len(stack)==0:
return "stack empty"
else:
return stack.pop()
push(stack, data)
print(pop(stack))
19. Write a function in Python PUSH(Num), where Num is a list of numbers. From this list
push all numbers divisible by 5 into a stack implemented by using a list. Display the stack if
it has atleast one element, otherwise display appropriate error message.
For example:
If the list Num is:
[66, 75, 40, 32, 10, 54]
The stack should contain:
[75, 40, 10]
ANS:
def PUSH(num):
s=[]
for x in range(0, len(num)):
if num[x]%5 ==0:
s.append(num[x])
if len(s) == 0:
print("Empty Stack")
else:
print(s)
PUSH([66,75,40,32,10,54])
20. Write functions in Python, MakePush(Package) and MakePop(Package) to add a new
Package and delete a Package from a List of Package Description, considering them to act
as push and pop operations of the Stack data structure.
ANS:
def MakePush(Package):
a= int(input("Enter package title:"))
Package.append(a)
def MakePop(Package):
if(Package ==[]):
print("Stack empty")
else:
print("deleted element:", Package.pop())

You might also like