12th Standard CBSE Syllabus & Materials
12th Standard CBSE
CBSE 12th Economics Government Budget and the Economy Previous year Question Papers Study Material - QB365 Set A
NEW12th Standard CBSE
CBSE 12th Computer Science Interface Python with MySQL - New Previous year Question Papers Study Material - QB365 Set A
NEW12th Standard CBSE
CBSE 12th Computer Science Database Concept - New Previous year Question Papers Study Material - QB365 Set A
NEW12th Standard CBSE
CBSE 12th Computer Science Data Communication - New Previous year Question Papers Study Material - QB365 Set A
NEW12th Standard CBSE
CBSE 12th Computer Science Functions - New Previous year Question Papers Study Material - QB365 Set A
NEW12th Standard CBSE
CBSE 12th Computer Science Python Revision Tour I - New Previous year Question Papers Study Material - QB365 Set A

Published on: 20/08/2026
Download CBSE Class 12th Standard CBSE Computer Science question papers, sample papers, important questions, and previous year solved papers in PDF format. Get free study materials, NCERT solutions, and exam preparation resources for Class 12th Standard CBSE Computer Science
Questions + Answers key
Take MCQ Computer Science Test

1.
(a) A stack named FruitStack, implemented using list, contains records of some fruits. Each record is represented as a dictionary with keys 'Name', 'Origin', 'Price', and 'Expiry'. A sample record is given here:
{'Name': 'Apple', 'Origin': 'France', 'Price': 120, 'Expiry' : '12-08-2025'}
Write the following user-defined functions in Python to perform the specified operations on FruitStack:
(i) push_fruit(FruitStack, Fruit) This function takes the stack FruitStack and a new record Fruit as arguments and pushes the record stored in Fruit onto FruitStack if the Price is less than 100.
(ii) pop_fruit(FruitStack) This function pops the topmost record from the stack and returns it. If the stack is already empty, the function should display "UNDERFLOW".
(iii) display(FruitStack) This function displays all the elements of the stack starting from the topmost element. If the stack is empty, the function should display 'EMPTY STACK'.
Or
(b) Write a Python program to accept 10 integers from the user. If the entered number is a three-digit even integer, push it onto a stack. After all inputs are taken, pop all the three-digit even integers from the stack and display them. For example, if the user enters 12, 31, 320, 457, 6, 92, 924, 220, 1, 218, then the stack should contain:
320, 924, 220, 218
and the output of the program should be:
218 220 924 320
2.
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 display appropriate error message.
3.
Alam has a list containing 10 integers. You need to help him create a program with separate user the given defined functions to perform operations based on this list.
Traverse the content of the list and push the even numbers into a stack. 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
N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
4.
(a) 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 user-defined 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.
Or
(b) Write the following user-defined functions in Python:
(i) 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.
(ii) 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.
(iii) 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'.
5.
The stack Admissionstack [ ] is a list implement stack comprising of student records of the following structure: [Rno, Name, Class, Grade]
Define functions for the following:
(a) enterstack(slst) Function to push a student record to the stack only if the student has grade "A".
(b) getstack( ) Function to pop and show the topmost student of the stack.
(c) peepstack( ) Function to display all the student records without removing any record.
Or
(i) Define the operations possible on a stack.
(ii) Define a function push2_5( ) to push numbers into a stack , only if the numbers
end with 2 or 5
6.
Sukanya 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) (i) Push the keys (name of the student) of the dictionary into a stack, where the corresponding value (marks) is greater than 75.
(ii) 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, "B0B": 89, "ALI" : 65, "ANU" : 90, "TOM" : 82}
The output from the program should be
TOM ANU BOB OM
Or
(B) Write a program to accept as many city names from the user and push them into a stack, only if the city names are palindromes.
(A palindrome is a word which is same as its reverse).
7.
(a) A dictionary Emp contains names and salaries of employees. Write Python functions to perform the following operations using a stack Stack:
(i) push_emp(Stack, EmpDict) Push the names of employees whose salary is greater than 50,000 onto the stack.
(ii) pop_emp(Stack) Pop and return the topmost element. If the stack is empty, display "Stack Underflow".
(iii) display_emp(Stack) Display all elements of the stack without deleting them. If the stack is empty, display "Empty Stack".
Example:
Emp = {"John":60000, "Amy":45000,
"Raj":55000, "Sara":40000}
Stack after pushing: ["John", "Raj"]
Or
(b) A list NumList contains integers. Write Python functions to:
(i) push_even(Stack, NumList) Push all even numbers from the list onto the stack.
(ii) pop_num(Stack) Pop and return the topmost number. If the stack is empty, display "Stack Underflow".
(iii) display_stack(Stack) Display all numbers without deleting them. If the stack is empty, display "Empty Stack".
Example:
NumList= [12, 17, 20, 33, 50]
Stack after pushing: [12, 20, 50]
8.
(a) Riya is developing a Python program to help her teacher manage the names of students who have submitted their homework. She uses a stack named HWStack to store the student names.
Write a Python function manage_homework(names) that performs the following operations:
(i) Pushes each name from the list names onto the stack.
(ii) Displays all names popped from the stack one by one, until the stack becomes empty, followed by the message "No more submissions left!"
For example:
If names = ["Amit", "Neha", "Karan"]
Output should be:
Karan
Neha
Amit
No more submissions left!
Or
(b) Write a Python program to manage the stack of recently opened files in a text editor.
Perform the following operations using functions:
(i) push_file(FileStack, filename) To add a new file to the top of the stack.
(ii) pop_file(FileStack) To remove and display the most recently opened file.
If the stack becomes empty after popping, display "No files left to close!"
9.
(a) A list contains following record of customer:
[Customer_name, Room Type]
Write the following user defined functions to perform given operations on the stack named 'Hotel'
(i) Push_Cust ( ) To Push customers' names of those customers who are staying in 'Delux' Room Type.
(ii) 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
(b) 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 cases like Tata, TaTa, etc.) to the stack.
For example:
If the dictionary contains the following data
Vehicle={"Santro": "Hyundai", "Nexon":
"TATA", "Safari": "TaTa"}
The stack should contain
Safari
Nexon
10.
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.
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
11.
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 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
12.
(A) You have a stack named BooksStack that contains records of books. Each book record is 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:
(I) push_book(BooksStack, new_book) This function takes the stack BooksStack and a new book recordnew_book as arguments and pushes the new book record onto the stack.
(II) 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".
(III) 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
(B) Write a Python program to input an integer and display all its prime factors in descending order, using a stack.
For example, if the input number is 2100, the output should be: 7 5 5 3 2 2 (because prime factorization of 2100 is 7 × 5×5×3×2×2)
Hint Smallest factor, other than 1, of any integer is guaranteed to be prime.
13.
A stack NumStack contains numbers [10, 20, 30, 40]. Perform the following operations:
1. Pop the top element
2. Push 50
14.
Rohit has a stack named BooksStack to manage his reading list. Each book is represented as [Book_Title, Author_Name, Year]. Perform the following operations:
1. Push ["Python Basics", "John Smith", 2021].
2. Push ["Data Structures", "Alice Brown", 2019].
3. Display the topmost book.
15.
Consider the following stack of characters, where STACK is allocated N= 8 memory cells.
STACK : A,C,D,F,K, ..., ..., ...
Describe the STACK at the end of the following operations. Here, Pop and Push are algorithms for deleting and adding an element to the stack.
(i) Pop (STACK, ITEM)
(ii) Pop (STACK, ITEM)
(iii) Push (STACK, L)
(iv) Push (STACK, P)
(v) Pop (STACK, ITEM)
(vi) Push (STACK, R)
(vii) Push (STACK, S)
(viii) Pop (STACK, ITEM)
16.
Write a program to create a Stack for storing only odd numbers out of all the numbers entered by the user. Display the content of the Stack along with the largest odd number in the Stack.
(Hint Keep popping out the elements from stack and maintain the largest element retrieved so far in a variable. Repeat till Stack is empty)
17.
Write a program to reverse a string using stack.
18.
Find the output of the following code:
(a) result=0
numberList=[10,20,30]
numberList.append(40)
result=result + numberList.pop()
result=result+numberList.pop()
print("Result=",result)
(b) answer=[ ];
output=" answer.append("T")
answer.append('A')
answer.append('M')
ch=answer.pop( )
output=output+ch
ch=answer.pop( )
output=output+ch
ch=answer.pop( )
output-output+ch
print("Result=",output)
19.
Write the following user-defined functions in specified operations on Python to perform the the stack NumStack:
(I) push_num(NumStack, new_num) This function takes the stack NumStackand a new number as arguments and pushes the new number onto the stackonly if it is even
(II) pop_num(NumStack) This function pops the topmost number from the stack and returns it. If the stack is already empty, the function should display "Underflow".
(III) peep(NumStack) This function displays the topmost element of the stack without deleting it. If the stack is empty, the function should display 'None'.
20.
Write a program to implement a stack for these book details (bookno, bookname). That is, now each item node of the stack contains two types of information - a bookno and its name. Just implement push and display operations.
21.
A list containing records of products as
L= [(Laptop", 90000), ("Mobile, 30000), (“Pen'; 50), ("Headphones", 1500)]
Write the following user-defined functions to perform operations on a stack named Product to:
I. Push_element( ) - To push an item containing the product name and price of products costing more than 50 into the stack.
Output [('Laptop', 90000), ('Mobile', 30000), ('Headphones', 1500)]
II. Pop_element( ) To pop the items from the stack and display them. Also, display "Stack Empty" when there are no elements in the stack.
Output ('Headphones',1500)
('Mobile', 30000)
('Laptop', 90000)
Stack Empty
22.
Write Add new(Book) and Remove(Book) methods in Python to Add a new Book and Remove a Book from a List of Books, considering them to act as PUSH and POP operations of the data structure stack.
23.
Millions of computer science students have taken a course on algorithms and data structures, typically the second Course after the introductory programming course. One of the basic data structures in such a course is stack. The stack holds a special place in the emergence of computing as a science. The stack can be used in many computer applications, a few of which are listed below:
• In recursive function
• When function is called.
• Expression conversion such as - Infix to Postfix, Infix to Prefix, Postfix to Infix, Prefix to Infix.
In stack, insertion operation is known as Push whereas deletion operation is known as Pop.
Code l
def push (Country. N):
Country. ________(len (Country).N)) #Statement 1
#Function Calling
Country = [ ]
C-['Indian', 'USA'. 'UK'. 'Canada'. 'Sri Lanka']
for i in range (0. len(C). ______________ ): # Statement 2
push (Country. C[i])
print (Country)
Output
['Indian, 'UK', 'Sri Lanka']
Code 2
def pop (Country):
if ________________ : # Statement 3
return "Under flow"
else:
return Country. _________________() # Statement 4
for i in range (len (Country) + 1):
print (____________) # Statement 5
Output
Sri Lanka
UK
Indian
Under flow
Fill the above statements based on given questions.
(i) Identify the suitable code for the blank of
Statement 1.
A .append( )
B .insert( )
C .extend( )
D .append(len (Country), N)
(ii) Fill the Statement 2, to insert the alternate element from Country list.
A 3
B 0
C -1
D 2
(iii) Fill the Statement 3, to check the stack is empty.
A Country = [ ]
B Country.isEmpty( )
C len(Country)==0
D None of these
(iv) Fill the Statement 4, to delete an element from the stack.
A pop(1)
B pop( )
C del country[1]
D Country.delete(1)
(v) Fill the Statement 5, to call the pop function.
A pop(C)
B pop(Country)
C call pop(Country)
D def pop(Country)
24.
Read the following passage and answer the questions that follow. Lists are the container which store the heterogeneous elements of any type as integer,
character, floating point elements of a list are represented by enclosing them in square brackets [ ].
Consider the following list Python
L=[13, 3.45, "Tree", "Amar" , [10, 8.91, "Apple"], 456]
(i) The output of L[-2]will be
A 10
B 8.91
C [10, 8.91, 'Apple']
D 3.45
(ii) To get value 8.91 from the list, the python statement will be
A L4][1]
B L[-2][-2]
C Both a) and b)
D None of these
(iii) The length of the list is
A 6
B 8
C 18
D None of these
(iv) print(len(L[2])==len(L[3]))will print
A False
B True
C Error
D None of these
(v) The output of print (L[1 :5:2]) will be
A [3.45, 'Amar]
B [3.45, Amar, 456]
C [3.45, 'Tree, Amar, 10, 8.91]
D Error
1.
(a) # Function to push fruit onto stack
if Price < 100
def push_fruit(FruitStack, Fruit):
if Fruit['Price'] < 100:
FruitStack.append(Fruit)
else:
print("Fruit not added
(Price >= 100)")
# Function to pop topmost fruit
def pop_fruit(FruitStack):
if len(FruitStack) == 0:
print("UNDERFLOW")
return None
else:
return FruitStack.pop()
# Function to display stack from top
to bottom
def display(FruitStack):
if len(FruitStack) == 0:
print("EMPTY STACK")
else:
print("Stack elements (Top to
Bottom):")
for i in range(len
(FruitStack)-1, -1, -1):
print(FruitStack[i])
# ......- Example Usage
FruitStack = [ ]
f1 = |'Name': 'Apple', 'Origin':
'France', 'Price': 120, 'Expiry':
'12-08-2025')
f2 = {'Name': 'Banana', 'Origin':
'India'. 'Price': 40. 'Expiry':
'10-04-2025'।
push_fruit(FruitStack, f1)
# Won't be added
push_fruit(FruitStack. f2)
# Will be added
display(FruitStack)
print("Popped:",
pop_fruit(FruitStack))
display(FruitStack)
(b) # Initialize stack
stack = [ ]
# Input 10 integers
for i in range(10):
num = int(input("Enter number: "))
# Check if number is 3-digit and
even
if num >= 100 and num <= 999 and
num % 2 == 0:
stack.append(num)
# Pop and display elements
print("Output:")
while len(stack) > 0:
print(stack.pop(), end=" ")
2.
Python function PUSH(Arr) that pushes numbers divisible by 5 into a stack (list) and displays the stack or an error message:
def PUSH(Arr) :
stack = [ ]
# Initialize an empty stack
for num in Arr :
if num % 50 == :
# Check if the number is divisible by 5
stack.append(num)
# Push the number into the stack
if stack :
# If the stack contains at least one element
print ("Stack:", stack)
else:
print("Error: No numbers divisible by 5.'' )
Example:
PUSH([1, 5, 10, 7, 15])
Output :
Stack: [5, 10, 15]
If there are no numbers divisible by 5 in the list:
PUSH ([1, 2, 3, 7])
Output:
Error: No numbers divisible by 5.
3.
def PUSH (S,N) :
S . append (N)
def POP(S) :
if S ! = [ ] :
return S.pop ( )
else :
return None
ST = [ ]
fork in N :
if k%2==0 :
PUSH (ST , k)
while True :
if ST! = [ ] :
print(POP(ST), end=" ")
else:
break
4.
(a) (i) def push_Clr(ClrStack, new_Clr):
ClrStack.append (new_Clr)
(ii) def pop_Clr(C)rStack) :
if is Empty (ClrStack) :
print ("Underflow")
return None
return ClrStack.pop ( )
(iii) def isEmpty(ClrStack) :
return len(ClrStack) == 0
Or
(b) (i) def push_trail (N, myStack) :
p = [- 5 : ] # This slice will be an empty list
myStack.extend(p)
(ii) def pop_one(myStack) :
if len (myStack) == 0 :
print("Stack underflow")
return None
else:
item = myStack.pop ( )
return item
(iii) def display_all(myStack) :
if len(myStack) == 0 :
print("Stack is Empty")
else
top = len(myStack) - 1
print("top ->", top)
for p in range(top 1.-1.-1):
print(myStack[p])
5.
(a) def enterstack(slst) :
if slst[3]=="A" :
Admissionstack.append(slst)
(b) def getstack ( ) :
if Admissionstack == [ ] :
print("No students")
else:
Admissionstack.pop( )
(c) def peepstack ( ):
if Admissionstack==[ ]:
print("No students")
else:
p= len(Admissionstack)-1
while p>=0 :
print(Admissionstack[p])
p-=1
Or
(i) A stack allows the following operations:
Push( ) This function pushes an element into the stack keeping the LIFO principle, which means the element is pushed to the top of the stack.
Pop( ) This function takes out the topmost element from the stack and displays it.
Traversal ( ) This function displays each of the stack contents from top index to 0 with the LIFO principle. It does not remove the elements.
(ii) stack = [ ]
def push2_5(n) :
if n%10==2 or n%10-5 :
stack.append(n)
6.
(A) (i)
R= {"OM":76, "JAI" : 45, "BOB" : 89, "ALI" : 65, "ANU" : 90, "TOM" : 82}
def PUSH (S,N):
S.append (N)
(ii) 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
Or
(B) palinstack=[ ]
def pushcity(n) :
palinstack.append(n)
ans='y'
while ans=='y':
n=input ("Enter a city:")
if n==n [: :-1]:
pushcity(n)
ans-input("Add more (y/n)")
7.
(a) (i) def push_emp(Stack. EmpDict):
for name in EmpDict:
if EmpDict[name]> 50000
Stack append(name)
(ii) def pop_emp(Stack)
if not Stack:
print("Stack Underflow")
return None
return Stack .pop( )
(iii) def display_emp(Stack):
if not Stack :
print("Empty Stack")
else :
print("Stack contents". Stack)
Or
(b) (i) def push_even (Stack. NumList):
for num in NumList:
if num % 2 == 0:
Stack.append(num)
(ii) def pop_num(Stack):
if not Stack :
print ("Stack Underflow")
return None
return Stack.pop( )
(iii) def display_stack(Stack) :
if not Stack :
print("Empty Stack")
else :
print("Stack contents:". Stack)
8.
(a) (i) def manage_homework(names) :
HWStack [ ]
for name in names :
HWStack.append(name)
(ii) while HWStack:
print(HWStack.pop( ) )
print("No more submissions left!")
# Example
manage_homework ( ["Amit", "Neha", "Karan"])
Or
(b) (i) FileStack = [ ]
def push_file(FileStack, filename):
FileStack.append(filename)
(ii) def pop_file(FileStack):
if not FileStack:
print("No files left to close!")
else:
print("Closed", FileStack.pop( ) )
# Example
push_file(FileStack, "notes.txt" )
push_file(FileStack, "project.py" )
pop_file (FileStack)
pop_file (FileStack)
pop_file (FileStack)
9.
(a) L = [['Siddharth', 'Delux'], ['Rahul". 'Standard']. ['Jerry'. 'Delux']]
Hotel = [ ]
(i) def Push_Cust( ):
for cust in L:
if cust[1]=='Delux':
Hotel.append(cust [0])
(ii) def Pop_Cust( ):
while len(Hotel)>0:
print(Hotel .pop( ) )
print("Underflow")
Push_Cust( )
Pop_Cust( )
Or
(b) Vehicle-("Santro" : "Hyundai". "Nexon": "TATA". "Safari" : "TaTa"}
stack = [ ]
def Push (V):
for i in V:
if V[1].upper()== "TATA":
stack.append(i)
print(stack)
Push(Vehicle)
10.
travel = [ ]
(i) def Push_element(NList):
for i in NList:
if i[1]!="India" and 1[2]<3500:
travel . append([i[0],i[1]])
(ii) def Pop_element( ) :
while len(travel) :
print (travel . pop( ) )
else :
print("Stack Empty")
11.
# Define the stack and input list
Nums [1234, 12345, 67890. 12. 567890, 123]
BigNums = [ ]
(i) def PushBig( ):
for N in Nums:
if N >= 10000:
# Check if the number is 10000 or greater
BigNums.append(N)
(ii) def PopBig( ) :
while BigNums :
print(BigNums.pop( ) )
print( "Stack Empty" )
# Test the functions
PushBig( )
PopBig( )
12.
(A) (I) def push_book (BooksStack, new_book):
BooksStack.append(new_book)
Here the stack is implemented using a stack.
Hence the append() function is used to add the new element at the top of the stack.
(II) def pop_book (BooksStack):
if not BooksStack:
print("Underflow")
else:
return BooksStack.pop( )
Here the stack is implemented using a stack.
The pop( ) function removes and displays the last element of a list. Hence the pop( ) function is used here to take out the topmost element of the stack
(III) def peep (BooksStack):
if not BooksStack:
print("None")
else
print(BookStack[-1])
Since the topmost element has to be displayed without removing, the pop() function cannot be used here. Instead the BookStack[-1] statement prints the last element of the list that has index -1.
Or
(B) n=int(input("Enter an integer: "))
s =[ ] #stack
f = 2
while n>1:
if n%f ==0:
s.append(f)
n //=f
else:
f +=1
while s:
print(s.pop().end=' ')
To find the prime factorization the number is repeatedly divided to find the clear division, starting from f = 2 When no longer divisible by 2 it is divided by the next prime factor and so on. All such factors are pushed into the stack. Finally the stack contents are popped.
13.
NumStack = [10, 20, 30.40]
def push(stack, value):
stack.append(value)
def pop(stack):
if stack:
print(stack.pop( ) )
else:
print("Stack Empty")
# Operations
pop(NumStack)
push(NumStack, 50)
print(NumStack)
14.
BooksStack = [ ]
def push_book(stack, new_book):
stack. append(new_book)
def peep(stack):
if stack:
print(stack[-1])
else:
print("None")
# Operations
push_book (BooksStack, ["Python Basics", "John Smith", 2021])
push_book (BooksStack, ["Data Structures","Alice Brown", 2019])
print("Topmost Book:")
peep(BooksStack)
15.
The stack contents will be as follows after the operations of stack
(i) STACK : A, C, D, F
(ii) STACK : A, C, D
(K is deleted) (F is deleted)
(iii) STACK: A, C, D, L
(iv) STACK: A, C, D, L, P
(L is inserted) (P is inserted)
(v) STACK: A, C, D, L
(vi) STACK: A, C, D, L, R
(P is deleted) (R is inserted)
(vii) STACK: A, C, D, L, R, S
(S is inserted)
(viii) STACK: A, C, D, L, R
(S is deleted)
16.
# Function to create a Stack for odd numbers
def store_odd_numbers ( ):
stack = [ ]
n = int(input("Enter the number of elements: "))
# Input numbers and push only odd numbers to stack
for _ in range(n):
num = int(input("Enter a number: "))
if num % 2 ! = 0:
stack.append(num)
print("Stack contents (Odd numbers):",stack)
# Finding the largest odd number
largest_odd=None
while stack :
current stack.pop( )
if largest_odd is None or current >largest_odd:
largest_odd = current
print("Largest odd number in the Stack:", largest_odd)
# Call the function
store_odd_numbers ( )
17.
def reverse_string(s):
stack = [ ]
# Push all characters of the string onto the stack
for char in s:
stack.append(char)
# Pop characters from the stack to get the revers string
reversed_str = ""
while stack:
reversed_str += stack.pop( )
return reversed_str
input_str "hello"
print("Reversed string:",
reverse_string(input_str))
18.
1. numberList starts as [10, 20, 30].
2. numberList.append(40) adds 40 to the list, so numberList becomes [10, 20, 30, 40].
3. numberList.pop() removes and returns the last item (40), so result 0+40=40.
4. numberList.pop() removes and returns the last item (30), so result = 40+30= 70.
5. The final print statement outputs Result= 70.
(b) The list answer starts as [T', 'A', 'M'].
The pop() method removes the last element from the list and appends it to output.
The order of pops is:
1. 'M' is popped first, then added to output.
2. 'A' is popped, added to output.
3. "T'' is popped, added to output.
Thus, the result is 'MAT'.
19.
(I) def push_num(NumStack, new_num)
if new_numleft==0:
NumStack.append(new_num)
(II) def pop_num(NumStack):
if not NumStack:
print("Underflow")
else:
return NumStack.pop( )
(III) def peep(NumStack):
if not NumStack:
print("None")
else:
print(NumStack[-1])
20.
def isempty(stk):
if stk == [ ] :
return True
else:
return False
def pushbook(stk, item):
stk.append(item)
def displaybook(stk):
if isempty(stk):
print("Stack Empty")
else:
print("Book No... Book Name")
for a in range(len(stk)-1, -1, -1):
print(stk[a])
stk = [ ]
while True:
print("\nBook Stack Menu")
print("1. Add a book")
print("2. Display list")
print("3. Exit")
ch = int(input("Enter your choice 1-3: "))
if ch == 1:
bno = input("Enter book no: ")
bname = input("Enter book name: ")
item = [bno, bname]
pushbook(stk, item)
input("Book added. Press Enter to continue...")
elif ch == 2:
displaybook(stk)
input("Press Enter to continue...")
elif ch == 3:
break
else:
print("Invalid choice!")
input("Press Enter to continue...")
21.
I. L=[("Laptop", 90000),("Mobile", 30000).("Pen",
50). ("Headphones". 1500)]
product = [ ]
defPush_element(L):
for i in L:
if i[1] > 50:
product.append(i)
print(product)
II. defPop_element (product):
while product:
print(product.pop())
else:
print("Stack Empty")
22.
books=[ ]
defAddnew (books,name):
books.append (name)
print("bookl:",name,"inserted")
def remove(books):
if books==[]:
print("stack is empty")
else:
print("book:",books.pop ( ), "deleted ")
23.
(i) (B) The Statement 1 used under the push() operation. The Push operation of stack is used to insert element in the stack.
(ii) (D) The alternate element from the country list C will be 2 because the list starts with 0.
(iii) (C) The stack will be considered as empty, if all the elements are popped up from stack and its length has become 0.
(iv) (B) Statement 4 is a part of pop function. If condition is used to check whether stack is empty or not. If not then code will execute else part and pop element from stack.
(v) (B) The Statement 5 will call pop function, which is already declared as Code 2 and taking a parameter country list
24.
(i) (C) As it is list within a list.
(ii) (C) Both are correct as L[4][1] and L[-2] [-2] access the same value from the list as 8.91.
(iii) (A) As the list inside another list is taken as one element, thus there are 6 total items in the list L.
(iv) (B) As both len(L[2] and len(L[3]) represents same length so the output on the screen will be true.
(v) (A) The output of the print command will be [3.45, 'Amar'] as the indexing corresponds to this items in the list.
12th Standard CBSE Syllabus & Materials
12th Standard CBSE
CBSE 12th Business Studies Planning Important Questions And Answers Study Material - QB365 Set A
NEW12th Standard CBSE
CBSE 12th Business Studies Business Environment Important Questions And Answers Study Material - QB365 Set A
NEW12th Standard CBSE
CBSE 12th Business Studies Principles of Management Important Questions And Answers Study Material - QB365 Set A
NCERT Books
Syllabus
Exam Pattern
Sample Question Papers
Previous year Question Papers
Important Notes
MCQ Practice test
NCERT Exemplers
Case study Questions
Image Based Questions
Passage based Questions
HOT Questions
Value Based Questions
Model Questions Papers
NCERT ( Book Back ) Questions
Assertion and Reason
Important Questions And Answers
CBSE 12th Standard CBSE Subjects
CBSE Standards