0% found this document useful (0 votes)
1K views

Chapter 9 Important Questions

The document contains 13 questions and solutions related to using stacks as a data structure in Python. The questions involve creating functions to perform push and pop operations on stacks implemented as lists. The questions demonstrate pushing and popping keys of dictionaries and elements of lists onto stacks based on certain criteria, such as dividing by a number. Sample inputs and outputs are provided for testing the solutions.

Uploaded by

Bolt FF
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views

Chapter 9 Important Questions

The document contains 13 questions and solutions related to using stacks as a data structure in Python. The questions involve creating functions to perform push and pop operations on stacks implemented as lists. The questions demonstrate pushing and popping keys of dictionaries and elements of lists onto stacks based on certain criteria, such as dividing by a number. Sample inputs and outputs are provided for testing the solutions.

Uploaded by

Bolt FF
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

CHAPTER 9 – DATA STRUCTURE

IMPORTANT QUESTIONS AND ANSWERS


1. BCCI has created a dictionary containing top players and their runs as key value pairs of cricket team.
Write a program, with separate user defined functions to perform the following operations:
 Push the keys (name of the players) of the dictionary into a stack, where the corresponding value
(runs) is greater than 49.
 Pop and display the content of the stack.
For example: If the sample content of the dictionary is as follows:
SCORE= {"KAPIL":40, "SACHIN":55,"SAURAV":80, "RAHUL":35, "YUVRAJ":110}
The output from the program should be:
YUVRAJ SAURAV SACHIN
Solution:
SCORE={"KAPIL":40,"SACHIN":55 , "SAURAV":80,"RAHUL":35, "YUVRAJ":110 }
def PUSH(S,R):
S.append(R)
def POP(S):
if S!=[]:
return S.pop()
else:
return None #Message
ST=[ ]
for k in SCORE:
if SCORE[k]>49:
PUSH(ST,k)
while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break
2. Vikram has a list containing 10 integers. 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 ODD 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:
35 79 21 13
Solution:
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
3. YASH MOTORS have a dictionary of top performer EMPLOYEES and their SALES of as key value
pairs of COMPANY. Write a program, with separate user defined functions to perform the following
operations:
 Push the keys (name of the EMPLOYEE) of the dictionary into a stack, where the corresponding
value (SALES) is greater than 500000.
 Pop and display the content of the stack.
For Example: If the sample content of the dictionary is as follows:
SALES= {"SUNIL":700000,"ROHIT":400000, "RAJEEV":350000,"MAYANK":750000,
"RAHUL":1000000}
The output from the program should be:
RAHUL MAYANK SUNIL
Solution:
SALES={"SUNIL":700000,"ROHIT":400000, RAJEEV":350000,"MAYANK":750000,
RAHUL":1000000}
def PUSH(STK,S):
STK.append(S)
def POP(STK):
if STK!=[]:
return STK.pop()
else:
return None
ST=[]
for k in SALES:
if SALES[k]>500000:
PUSH(ST,k)
while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break
4. Saroj 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 into a stack, which are divisible by 5.
 Pop and display the content of the stack.
For Example:
If the sample Content of the list is as
follows:
N=[2,5,10,13,20,23,45,56,60,78]
Sample Output of the code should
be: 60 45 20 10 5
Solution:
N=[3,5,10,13,21,23,45,56,60,78]
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%5==0:
PUSH(ST,k)
while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break
5. A programmer wants to prepare a stack from given list of integer elements only for the numbers which
are divisible by 3. Help him create a program with a user defined functions to perform the following
operations based on this list.
 Traverse the content of the list and push the numbers into a stack which are divisible by 3.
 Pop and display the content of the stack.
For Example: If the sample Content of the list is as follows:
N=[3,5,10,13,21,23,45,56,60,78]
Sample Output of the code
should be: 60 45 21 3
Solution:
N=[3,5,10,13,21,23,45,56,60,78]
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%3==0:
PUSH(ST,k)
while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break
6. JAVED 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) are more than 79.
 Pop and display the content of the stack.
For example:
If the sample content of the dictionary is as follows:
R={"RAKESH":70, "OMESH":50,"VISWAS":70, "ANITA":80,"ANUSHRI":90}
Solution:
R={"RAKESH":70, "OMESH":50,"VISWAS" :70, "ANITA":80,"ANUSHRI":90}
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
7. Write a function push(student) and pop(student) to add a new student name and remove a student name
from a list student, considering them to act as PUSH and POP operations of stack Data Structure in
Python.
Solution:
st=[ ]
def push(st):
sn=input("Enter name of student")
st.append(sn)
def pop(st):
if(st==[]):
print("Stack is empty")
else:
print("Deleted student name :",st.pop())
#________Main ______
push(st)
print('After push :',st)
pop(st)
print('After pop: ',st)
Sample Output:
Enter name of student: ARNOLD
After push : ['ARNOLD']
Deleted student name : ARNOLD
After pop: []
8. Write a python program to read a line of text and Print it in reverse (Reverse word by word) using
stack.
Solution:
line=input("Enter any line of text : ")
stack=[]
for word in line.split():
print(word)
stack.append(word)
print("Stack : ", stack)
print("Total words are : ", len(stack))
n = len(stack)
for i in range(n-1, -1, -1):
print(stack[i], end=' ')
Sample Output:
Enter any line of text : hello how are you
hello
how
are
you
Stack : ['hello', 'how', 'are', 'you']
Total words are : 4
you are how hello
9. Write a menu driven program using function Qadd( ), and Qdisp( ) to add and display the record of
book using stack as data structure in python. Record of book store the following details: Book name,
Book Number and Book Price.
Solution:
book=[ ]
ch='y'
def Qadd(book):
bn=input("Enter book name")
bnum=int(input("Enter book number"))
bp=int(input("Enter book price"))
temp=[bn,bnum,bp]
book.append(temp)
def Qdisp(book):
l=len(book)
print("Book Name\tBook Number\tBook Price")
for i in range(0,l):
print(book[i][0],"\t\t",book[i][1],"\t\t",book[i][2])
while(ch=='y' or ch=='Y'):
print("1. Add Record\n")
print("2. Display Record\n")
print("3. Exit")
op=int(input("Enter the Choice: "))
if(op==1):
Qadd(book)
elif(op==2):
Qdisp(book)
elif(op==3):
break
ch=input("Do you want to enter more(Y/N) :")
OUTPUT
1. Add Record
2. Display Record
3. Exit
Enter the Choice :1
Enter book name: COMPUTER SCIENCE
Enter book number: 1001
Enter book price: 450
Do you want to enter more(Y/N): Y
1. Add Record
2. Display Record

3. Exit

Enter the Choice :2

Book Name Book Number Book Price

COMPUTER SCIENCE 1001 450


Do you want to enter more(Y/N): Y
1. Add Record
2. Display Record
3. Exit
Enter the Choice :3
10. Write a function in Python PUSH(Arr), where Arr is a list of numbers. From this list push all numb
divisible by 5 into a stack implemented by using a list. Display the stack if it has at least one element,
other display appropriate error message.
Solution:
def PUSH(Arr, value):
SM=[ ]
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)
11. Write functions in Python for PushS(List) and for PopS(List) for performing Push and Pop operations
with a stack of List containing integers.
Solution:
def PushS(List):
N=int(input("Enter integer"))
List.append(N)
def PopS(List):
if (List==[ ]):
print("Stack empty; UNDERFLOW!")
else:
print ("Deleted value:", List.pop())
12. Write a function in python, MakePush(Package) and MakePop(Package) to add a new Package and
delete Package from a List of Package Description, considering them to act as push and pop operations of
the Stack data structure.
Solution:
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())
13. Write Addnew(Book) and Remote(Book) methods in Python Added and Remove a Book from a list
of Books, considering them to act as PUSH and POP operations of the data structure Stack.
Solution:
Book=[ ]
def Addnew(s):
Name=Input("Enter Book Name:")
Book.append(Name)
def Remove(self):
if (Book == [ ]):
print ("Stack Empty, UNDERFLOW!")
else:
print ("Deleted Book Is", Book.pop())
14. Write a program to implement a stack for these book-details (bookno, book name). That is, now each
item node of the stack contains two types of information - a book and its name. Just implement Push and
display operations.
Solution:
“ “ “ Stack: implemented as a list
top: integer having position of topmost element in Stack ” ” ”
def cls():
print("\n"*100)
def IsEmpty( stk):
if stk == [ ]:
return True
else:
return False
def Push(stk, item):
stk.append(item)
top=len(stk)-1
def Display(stk):
If isEmpty(stk):
print("Stack empty")
else:
top=len(stk)-1
print(stk[top], "<- top")
for a in range(top-1, -1, -1):
print(stk[a])
#_____ Main____
Stack=[ ] #initially stack is empty
Top=None
while True:
cls()
print("STACK OPERATIONS")
print("1. Push")
print("2. Display stack")
print("3. Exit")
ch=int(input("Enter your choice (1-5):"))
if ch==1:
bno=int(input("Enter Book no. to be inserted :"))
bname= input("Enter Book name to be inserted :")
item [bno, bname] #creating a list from the input items.
Push(Stack, item)
input()
elif ch==2:
Display(Stack)
Input()
elif ch==3:
break
else:
print("Invalid choice!")
input()

15. 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
Solution:
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
16. Write a function in Python Push (nums), where nums is a list of numbers. From this list push all odd
numbers into a stack implemented by using a list. Display the stack if it has at least one element,
otherwise display appropriate error message.
Solution:
def Push(nums):
li =[]
for i in range(0,len(nums)):
if nums[i]%2!=0:
li.append(nums[i])
if len(li) == 0:
print('Stack is empty!!')
else:
print(li)
Push([10,15,20,25,30,35])
Note : Any correct code giving the same result is also accepted
17. Write a function in Python Popstack (names), where names is a stack implemented by a list of names.
The function returns the name deleted from the stack.
Solution:
def popStack(names) :
L = len(names)
if L==0:
print("Stack Underflow")
else:
val = names[L-1]
names.pop(L-1)
return val
res=popStack(['Harikaran','Balaji','Nikhil','Cathrine'])
print('Value returned:',res)
Note : Any correct code giving the same result is also accepted
18. A stack S contains Name of countries. Write a function POP(A), to remove Name from stack.
Function should handle underflow condition and should return removed element.
Solution:
def POP(A):
if len(A)==0:
print(“UNDERFLOW”)
else:
val=A.pop()
return val
19. Write a function PUSH(STACK,Name) to add new name to the STACK data structure . Also display
all the names having atleast 4 characters from the stack.
Solution:
def PUSH(STACK,Name):
STACK.append(Name)
#code for displaying
if len(STACK)==0:
print(“Empty stack”)
else:
top=len(STACK)-1
for i in range(top,-1,-1):
if len(STACK[i])>=4:
print(STACK[i] )
20. Write the definition of a user defined function PushNV(N) which accepts a list of strings in the
parameter N and pushes all strings which have no vowels present in it, into a list named NoVowel.
● Write a program in Python to input 5 Words and push them one by one into a list named all.
The program should then use the function PushNV( ) to create a stack of words in the list NoVowel so
that it stores only those words which do not have any vowel present in it, from the list All. Thereafter, pop
each word from the list NoVowel and display the popped word. When the stack is empty, display the
message "EmptyStack".
For example:
If the Words accepted and pushed into the list All are
['DRY', 'LIKE', 'RHYTHM', 'WORK', 'GYM']
Then the stack NoVowel should store
['DRY', 'RHYTHM', 'GYM']
And the output should be displayed as
GYM RHYTHM DRY EmptyStack
Solution:
def PushNV(N):
for W in N :
for C in W :
if C.upper() in 'AEIOU':
break
else:
NoVowel.append(W)
All=[]
NoVowel=[]
for i in range(5) :
All.append(input('Enter a Word: '))
PushNV(All)
while NoVowel :
print(NoVowel.pop(), end=' ')
else :
print('EmptyStack')
21. Write the definition of a user defined function Push3_5(N) which accepts a list of integers in a
parameter N and pushes all those integers which are divisible by 3 or divisible by 5 from the list N into
a list named Only3_5.
● Write a program in Python to input 5 integers into a list named NUM.
The program should then use the function Push3_5() to create the stack of the list Only3_5. Thereafter
pop each integer from the list Only3_5 and display the popped value. When the list is empty, display
the message "StackEmpty".
For example:
If the integers input into the list NUM are :
[10,6,14,18,30]
Then the stack Only3_5 should store
[10,6,18,30]
And the output should be displayed as
30 18 6 10 StackEmpty
Solution:
def Push3_5(N):
for i in N :
if i%3==0 or i%5==0 :
Only3_5.append(i)
NUM=[]
Only3_5=[]
for i in range(5):
NUM.append(int(input('Enter an Integer: ')))
Push3_5(NUM)
while Only3_5 :
print(Only3_5.pop(), end=' ')
else :
print('StackEmpty')

You might also like