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

Stack 3 Marks

Uploaded by

Purnima E
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views

Stack 3 Marks

Uploaded by

Purnima E
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Stack

Cbse board sample papers:


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
Ans:

2.
Ans:

Hotel=[]
Customer=[[“siddarth”:”delux”],[“Rahul”:”standard”],[“jerry”:”delux”]]
def push_cust():
for rec in customer:
If rec[1]==”Delux”:
Hotel.append(rec[0])
def pop_cust():
while len(Hotel)>0:
print(Hotel.pop())
else:
print(“Stack is empty”)

(or)
top=0
def push_cust(Hotel,customer):
global top
for rec in customer:
if rec[1]==”delux”:
Hotel.insert(top,rec[0])
top=top+1
def pop_cust(Hotel):
global top
while len(Hotel)>0:
print(Hotel.pop())
else:
print(“Stack is empty”)
3.

Ans:
Stack=[]
def push(vehicle):
for i in vehicle:
if vehicle[i].upper()==”TATA”:
stack.append(i)
(or)
Stack=[]
def push(vehicle):
for i in vehicle:
if vehicle[i] in (“TATA”,”TaTa”,”tata”,”Tata”):
stack.append(i)
Sample questions:
general

1. Predict the output with respect to the Stack implemented using list:
stk=[11,22,25,40,60,45]
(a) print(stk) Ans: [11,22,25,40,60,45]
(b) print(len(stk)) Ans: 6
(c) stk.pop() ; print(stk) Ans:45
[11,22,25,40,60]
(d) stk.append(30); print(stk) Ans: [11,22,25,40,60,30]

2. Predict the output of following print statement with respect to the Stack , if push() is used to append
the element in Stack and Top holding the greatest index value of Stack :
Record=[[11,"Rohit"],[12,"John"],[13,"Sonal"]]
print(len(Record)) Ans: 3
b. print(Record[Top]) Ans: [13,"Sonal"]
c. pop(); pop(); push([15,"Ronit"]); print(Record) [[11,"Rohit"],[15,"Ronit"]
d. print(Record[Top][1]) Ans: ’Ronit’
3. Predict the output of stack after performing the following operation:
Stk=[]
Push 5 Pop Push 7 Push 2 Push 10 Push 9 Pop Pop Push 5
(a)print(Stk) (b) print(Top)

Ans: a) [7,2,5] b) 5

4. Write a function to implement Push operation on stack.


Ans:
def PUSH(stk,student):
stk.append(student)
top=len(stk)-1

5. Write a function to implement Pop operation on stack.


Ans:
def pop(stk):
if stk==[]:
return "underflow"
else:
x=stk.pop()
if stk==[]:
top=None
else:
top=len(stk)-1
return x
6. Write a function in Python PUSH(Num), where Num is a list of integer numbers. From this list push
all positive even numbers into a stack implemented by using a list. Display the stack if it has at least
one element, otherwise display appropriate error message.
Ans:
def PUSH(Num):
s=[]
for x in Num:
if x%2==0 and x>0:
s.append(x)
if len(s)==0:
print("STACK EMPTY")
else:
print(s)
7. Write a function in Python POP(cities), where cities is a stack implemented by a list of city names for
eg. cities=[‘Delhi’, ’Jaipur’, ‘Mumbai’, ‘Nagpur’]. The function returns the value deleted from the
stack.
Ans:
def POP(cities):
#For empty stack
if (len(cities)==0):
print("Under flow")
else:
P=cities.pop()
if len(cities)==0:
Top=None
else:
Top=len(cities)-1
return P
8. 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.
Ans:
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)
9. Write a function in python, PushEl(e) to add a new element and PopEl(e) to delete a element from a
List , considering them to act as push and pop operations of the Stack data structure .
Ans:
def PushEl(element):
a=int(input("enter package title : "))
element.append(a)

def PopEl(element):
if (element==[]):
print( "Stack empty")
else:
print ("Deleted element:", element.pop())

10. Write a function POP(Book) in Python to delete a Book from a list of Book titles, considering it to act
as a pop operation of the Stack data structure.
Ans:
def POP(Book):
if (Book ==[]):
print(“Stack empty”)
else:
print(“Deleted element :”, Book.pop())

11. Write a function in Python PushBook(Book) to add a new book entry as book_no and book_title in the
list of Books , considering it to act as push operations of the Stack data structure.
Ans:
def PushBook(Book):
bno = input("enter book no : ")
btitle = input(“enter book title:”)
rec = [bno, btitle]
Book.append(rec)
print(Book)

12. Write a function AddCustomer(Name) in Python to add a new Customer information NAME into the
List of CStack and display the information.
Ans:
def AddCustomer(Name):
CStake.append(Customer)
if len(CStack)==0:
print (“Empty Stack”)
else:
print (CStack)

13. Write a function DeleteCustomer() to delete a Customer information from a list of


CStack. The function delete the name of customer from the stack
Ans:
def DeleteCustomer():
if (CStack ==[]):
print(“There is no Customer!”)
else:
print(“Record deleted:”,CStack.pop())

14. Write a function listchange(Arr)in Python, which accepts a list Arr of numbers , the function will
replace the even number by value 10 and multiply odd number by 5 .
Sample Input Data of the list is:
a=[10,20,23,45]
listchange(a,4)
output : [10, 10, 115, 225]
Ans:
def listchange(arr,n):
l=len(arr)
for a in range(l):
if(arr[a]%2==0):
arr[a]=10
else:
arr[a]=arr[a]*5

a=[10,20,23,45]
listchange(a)
print(a)
15. Write a function LShift(Arr,n) in Python, which accepts a list Arr of numbers and n is a numeric value by
which all elements of the list are shifted to left.
Sample Input Data of the list
Arr= [ 10,20,30,40,12,11], n=2
Output
Arr = [30,40,12,11,10,20]
Ans:
def LShift(Arr,n):
L=len(Arr)
for x in range(0,n):
y=Arr[0]
for i in range(0,L-1):
Arr[i]=Arr[i+1]
Arr[L-1]=y
print(Arr)

16. Write a function in python named PUSH(STACK, SET) where STACK is list ofsome numbers
forming a stack and SET is a list of some numbers. The functionwill push all the EVEN elements from
the SET into a STACK implemented byusing a list. Display the stack after push operation.
Ans:
def PUSH(STACK,SET):
for i in SET:
if i%2==0:
STACK.append(i)
Print(“updated stack is :”, STACK)

17. Write a function in python named POP(STACK) where STACK is a stackimplemented by a list of
numbers. The function will display the popped elementafter function call.Also, display “Stack Empty”
if there are no elements in the stack.
Ans:
def POP(STACK):
if STACK==[]:
print(“Stack is empty”)
else:
print(STACK.pop())

18. A stackBook contains the following details of various books – [book_no, book_title,
ook_price].Write a function PushBook(Book)in Python that inputs the book details from the user and
pushes into the stack. Also, display the stack elements.
Ans:
def PushBook(Book):
book_id=int(input("Enter book id: "))
book_title=input("Enter book title: ")
book_price = int(input("Enter price: "))
data=[book_id,book_title,book_price]
Book.append(data)
print("The stack: ",Book)
19. Write a python program using function to find the largest element in a list
and then reverse the list contents and display it. Don’t use in-built functions
for the program.
Ans:
def largest(L,n) :
max = L[0]
for i in range(1, n) :
if L[i] > max :
max =L[i]
return max
M = [10, 24, 45, 90, 98]
n = len(M)
max= largest(M, n)
print ("Largest in the given List is", max)
for i in range(n//2):
M[i],M[len(M)-1-i] = M[len(M)-1-i], M[i]#swapping elements
print('Reverse list:', M)

20. Write a code for the STACK PUSH and POP implementation.
a)Write functions AddPlayer(player) and DeletePlayer(player) in python to add and remove a player by
considering them as push and pop operations in a stack.Write a function to display the stack elements.
Ans:
def AddPlayer(player):
pn=input("enter player name:")
player.append(pn)
def DeletePlayer(player):
if player==[]:
print("No player found")
else:
return player.pop()
def display(player):
if player==[]:
print("Stack is Empty")
else:
top = len(player)-1
print(player[top],"-Top")
for i in range(top-1,-1,-1):
print(player[i])
21. Write a python program using function to demonstrate random() with dictionary. Should create the
dictionary of 5 keys:valus random character as key and ASCII as its value.
Ans:
import random
def createDict():
a={ }
for i in range(5):
x=random.randint(65,90)
x=chr(x)
n=random.randint(10,99)
a.update({x:n})
return a
dict =createDict()
print ("Dictionary :",dict)
(important**)
22. A list contains following records of students:
[Adm_no,SName,DOB,Mobile]
Write the following user defined function to perform given operations on the stack
named 'Admission':
i)PUSH() To insert an object containing admission number,student name and Mobile of
the students who's birth year is after 2008 to the stack. If stack holds more than 3 elements
show "stack is full"
ii) POP() To pop the object from the stack and display them in stack one by one.
For Example:
If the lists of students detail are :
["20221017","Guru","20-7-2008","9988779988"]
["20221018","Ragunath","06-8-2009","9977889988"]
["20221019","Jenifer","31-12-2007","9988996677"]
["20221020","Priya","21-10-2009","9966557864"]
The stack should contain
["20221017","Guru","9988779988"]
["20221018","Ragunath","9977889988"]
["20221020","Priya","9966557864"]
The output should contain
["20221017","Guru","9988779988"]
["20221018","Ragunath","9977889988"]
["20221020","Priya","9966557864"]
Stack is full

Ans:
status =[ ]
def Push_ele(stud):
if len(status) ≤ 3
if stud[2] ==2008:
L1=[stud[0],stud[1]]
Status.append(L1)
Else:
Print("Stack is Full")
def pop_ele():
num=len(status)
while len(status)!=0:
dele=status.pop()
print(dele)
num=num-1
else:
print("Stack Empty")
23. Write a function in python, makepush(var) and makepop(var) ,to add a new variable and
delete a variable from list of variables description, considering them to act as push and pop
operations of the stack data structure.
Ans:
def makepush(var):
a=int(input("Enter Variable name:"))
var.append(a)
def makepop(var):
if (var ==[ ]):
print(stack empty")
else:
print("Deleted Variable:",var.pop())
24. Write a function REP which accepts a list of integers and size of list and replaces elements having
even values with its half and elements having odd values with twice its value. eg: if the list contains
3, 4, 5, 16, 9
then the function should rearranged list as
6, 2,10,8, 18
Ans:
def REP (L, n):
for i in range(n):
if L[i] % 2 == 0:
L[i] /= 2
else:
L[i] *= 2
print (L)
25. Write a function which accept the two lists, and returns a list having only those elements that are
common between both the lists (without duplicates) in ascending order.
Make sure your program works on two lists of different sizes. e.g.
L1= [1,1,2,3,5,8,13,21,34,55,89]
L2= [20,1,2,3,4,5,6,7,8,9,10,11,12,13]
The output should be:
[1,2,3,5,8,13]
Ans: L1= [1,1,2,3,5,8,13,21,34,55,89]
L2= [20,1,2,3,4,5,6,7,8,9,10,11,12,13]
L3=[]
temp_L1=list(set(L1))
temp_L2=list(set(L2))
for i in temp_L1:
for j in temp_L2:
if i==j:
L3.append(i)
L3.sort()
print(L3)

26. Write a function GENERATE_INDEX(L), where L is the list of elements passed as argument to the
function. The function returns another list named ‘NewIndex’ that stores the indices of all even
Elements of L. For example: If L contains [22,7,9,24,6,5] The NewIndex will have - [0, 3, 4]
Ans:
def GENERATE_INDEX(L):
NewIndex=[]
for i in range(len(L)):
if L[i]%2==0:
NewIndex.append(i)
print(NewIndex)
GENERATE_INDEX([22,7,9,24,6,5])
27. Write a Python function CREATESTACK(L), which should create two lists SO and SE from the list L
containing integers. The stack SO should contain all the odd elements of the list L, and the stack SE
should contain all the even elements of the list L. Also, write a function POPSTACK( ) which should
pop and print all the elements of the stack SE, and print stack empty at the end.
For example, if the list L is [2,7,9,15,14]
Then SO should be [7,9,15]
SE should be [2,14]
Output of POPSTACK( ) function should be 14 2 Stack Empty

Ans:
SO,SE=[],[]
def CREATESTACK(L):
for i in L:
if i%2==0:
SE.append(i)
else:
SO.append(i)

def POPSTACK():
for i in range(len(SE)):
print(SE.pop(),end=' ')
print("Stack Empty")

CREATESTACK([1,2,4,6,7,9,13])
print("SO is: ",SO)
print("SE is: ",SE)
POPSTACK()

Output:

SO is: [1, 7, 9, 13]


SE is: [2, 4, 6]
6 4 2 Stack Empty

28. Write a Python function MYSTACK(d), which should accept a dictionary d of the form roll : name as
argument. The function should create a stack MYNAME having all the names containing ‘s’ or ‘S’.
Also, write a function POPSTACK( ) which should pop and print all the elements of the stack
MYNAME, and print stack empty at the end.

For example, if the dictionary d is {1: ‘Sunil’, 2:’Naman’, 3:’Anish’}


Then MYNAME should be [‘Sunil’, ‘Anish’]
Output of POPSTACK( ) function should be Anish Sunil Stack Empty
Ans:
MYNAME=[]
def MYSTACK(d):
for i in d:
if 's' in d[i].lower():
MYNAME.append(d[i])
def POPSTACK():
for i in range(len(MYNAME)):
print(MYNAME.pop(),end=' ')
print('Stack Empty')

MYSTACK({1: 'Sunil', 2:'Naman', 3:'Anish'})


POPSTACK()

29. Write a function LShift(Arr,n) in Python, which accepts a list Arr of numbers and n is a numeric value
by which all elements of the list are shifted to left. Sample Input Data of the list
Arr= [ 10,20,30,40,12,11],
n=2
Output Arr = [30,40,12,11,10,20]
Ans:
ef LShift(Arr,n):
L=len(Arr)
for x in range(0,n):
y=Arr[0]
for i in range(0,L-1):
Arr[i]=Arr[i+1]
Arr[L-1]=y
print(Arr)
Note : Using of any correct code giving the same result is also accepted.

30. 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.
Ans:
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)

31. 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.
Ans:
ef popStack(st) : # If stack is empty
if len(st)==0:
print("Underflow")
else:
L = len(st)
val=st[L-1]
print(val)
st.pop(L-1)
Note: Full marks can be awarded for any other correct logic.
32. Write definition of a method ODDSum(NUMBERS) to add those values in the list of NUMBERS,
which are odd.
Sample Input Data of the List
NUMBERS=[20,40,10,5,12,11]
OUTPUT is 16
Ans:
def ODDSum(NUMBERS):
s=0
for i in NUMBERS:
if i%2 !=0:
s=s+i
print(s)
Using any correct code giving the same result is also accepted

33. Write a function in Python PUSH(Num), where Num is a list of integer numbers. From this list push all
positive even numbers into a stack implemented by using a list. Display the stack if it has at least one
element, otherwise display appropriate error message.
Ans:
def PUSH(Num):
s=[]
for x in Num:
if x%2==0 and x>0:
s.append(x)
if len(s)==0:
print("STACK EMPTY")
else:
print(s)
34. Write a function in Python POP(cities), where cities is a stack implemented by a list of city names for
eg. cities=[‘Delhi’, ’Jaipur’, ‘Mumbai’, ‘Nagpur’]. The function returns the value deleted from the stack
Ans:
def POP(cities):
#For empty stack
if(len(cities)==0):
print("Under flow")
else:
l=len(cities)
c=cities[l-1]
print(c)
cities.pop(l-1)
35. Write a function in Display which accepts a list of integers and its size as arguments and replaces elements
having even values with its half and elements having odd values with twice its value .eg: if the list contains
5, 6, 7, 16, 9 then the function should rearranged list as 10, 3,14,8, 18
Ans:
def Display (X, n):
for i in range(n):
if X[i] % 2 == 0:
X[i] /= 2
else:
X[i] *= 2
print (X)
(½ mark for correct function header
1 mark for correct loop
1 mark for correct if statement
½ mark for logic part /statement)

36. Write a function in Display which accepts a list of integers and its size as
arguments and replaces elements having even values with its half and elements
having odd values with twice its value .
eg: if the list contains
5, 6, 7, 16, 9
then the function should rearranged list as
10, 3,14,8, 18
Ans:
def Push(STACK,SET):
for i in SET :
if i%2==0:
STACK.append(i)
print(“Updated stack is :”,STACK)

37. Write a function in python named POP(STACK) where STACK is a stack


implemented by a list of numbers. The function will display the popped element after function call.
Ans:
def POP(STACK):
if STACK==[] :
print(“Stack is empty”)
else:
print(STACK.pop())

½ marks for correct header


1½ marks for correct logic
½ mark for proper use of append or pop function
½ mark for correct output

38. Considering the dictionary storing the price of vegetables,


veg={‘potato’:30,’beans’:40,’carrot’:40,’cabbage’:20,’brinjal’:10,’tomato’:50,’drumstick’:60}
a) Write python function to build a stack costly by pushing the names of vegetables whose
price is > 40 from dictionary veg.
b) Pop and display the items in stack costly
Note:Write only 2 functions pushcostly(veg,costly) and popcostly(costly).Write appropriate
statements in the main part to call the functions.

def pushcostly(p,s):
for i in p:
if p[i]>40:
s.append(i)
def popcostly(s):
if s==[]:
print("Stack underflow")
else:
print("costly vegetables")
while(s):
print(s.pop())
return
veg={‘potato’:30,’beans’:40,’carrot’:40,’cabbage’:20,’brinjal’:10,’tomato’:50,’drumstick’:60}
costly= []
while True:
print ('''Menu
1.push
2.pop and display
3.exit''')
ch=int (input ("enter your choice"))
if ch==1:
pushprod(veg,costly)
elifch==2:
popdisplay(costly)
else:
break
39. 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}
Then the output will be: Umesh Vishal Ishika
Ans:
def push(stk,item):
stk.append(item)
def Pop(stk):
if stk==[]:
return None
else:
return stk.pop()
stk=[]
d={"Ramesh":58, "Umesh":78, "Vishal":90, "Khushi":60, "Ishika":95}
for i in d:
if d[i]>70:
push(stk,i)
while True:
if stk!=[]:
print(Pop(stk),end=" ")
else:
break
40. 1. Write a python function to delete an element from the stack.
2. Write a function to inspect an element from the stack.
3. Write functions AddPlayer(player) and DeletePlayer(player) in python to add and remove a

player by considering them as push and pop operations in a stack.


Ans:
1
def pop_stack(stk):
if stk==[]:
return "UnderFlow"
else:
e = stk.pop()
if len(stk)==0:
top = None
else:
top = len(stk)-1
return e
2
def peek(stk):
if stk==[]:
return "UnderFlow"
else:
top = len(stk)-1
return stk[top]
3
def AddPlayer(player):
pn=input("enter player name:")
player.append(pn)
def DeletePlayer(player):
if player==[]:
print("No player found")
else:
return player.pop()
41. Write a function sumcube(L) to test if an element from list L is equal to the sum of the cubes of its digits ie it
is an ”Armstrong number”. Print such numbers in the list.
If L contains [67,153,311,96,370,405,371,955,407]
The function should print 153,370,371,407
Ans:
def sumcube(L):
for i in L:
t=i
s=0
while t:
r=t%10
s=s+r**3
t=t//10
if s==i:
print(i,end=' ')
L=[67,153,311,96,370,405,371,955,407]
sumcube(L)
42. Vikram has a list containing 10 integers. You need to help him to create a program with
separate user defined functions to perform the following operations based on this list.
● pushnum() to Traverse the content of the list and push the numbers that are divisible by 5
into a stack.
● popnum() to Pop and display the content of the stack and display “Stack underflow” if
the stack is empty.
For Example:
If the sample Content of the list is as follows:
N=[10, 13, 34, 55, 21, 79, 98, 22, 35, 38]
Sample Output of the code should be:
35
55
10
Ans:
def pushnum(Num,stk):
for i in Num:
if i%5==0:
stk.append(i)
def popnum(stk):
if len(stk):
print("The elements of Stack")
while stk:
print(stk.pop())
else:
print("Stack Empty")
L=[10, 13, 34, 55, 21, 79, 98, 22, 35, 38]
stk=[]
pushnum(L,stk)
popnum(stk)
43. Write a function in Python, Push(Ride) where , Ride is a dictionary containing the details
of Cab ride , Ride={driver: billamt }.
The function should push the names of those driver names in the stack,INCENTIVE who
have billed greater than 400. Also display the count of names pushed into the stack
For example:
If the dictionary contains the following data:
Ride={‘Raghu’:389,’Anbu’:560,’Siraj’:768,’Syed’:450 }.
The stack INCENTIVE should contain
[‘Anbu’,’Siraj’,’Syed’]
The output should be:
The count of Drivers in the stack is 3
Ans:
def push(Ride):
for i in Ride:
if Ride[i]>400:
incentive.append(i)
print("The count of drivers in the stack",len(incentive))
print("The stack is")
for i in incentive[::-1]:
print(i)
Ride={'Raghu':389,'Anbu':560,'Siraj':768,'Syed':450 }
incentive=[]
push(Ride)

You might also like