You are on page 1of 22

DotPyEdu PLAY WITH PYTHON

DATA STRUCTURE
STACK (PUSH + POP)

LINEAR
x =[1,2,3,5,7,89,3,62,34,13,5, 7, 9]
data = 89; found =0
for i in x:
if i ==data:
found =1
if(found ==0):
print("Data not found")
else:
print("Data found")
BINARY
x =[1,2,3,5,7,8,9,10,12,14,15,18,20,22] if(x[mid]>data):
data = 9; found =0 last = mid-1
first=0; last =13 if(found ==0):
while (first<=last and found ==0): print("Data not found")
mid = int((first+last)/2) else:
print("M : ",mid," ,F: ", first ,",L: ",last) print("Data found")
if(x[mid]==data):
found =1
if(x[mid]<data):
first=mid+1

Page 1 of 22 EDUCATION FOR EVERYONE


DotPyEdu PLAY WITH PYTHON
INSERTION

I: DATA=[1,2,3,4,5,6,7]
print("D:",DATA)
length = len(DATA)
print( "Len:", length)
II: e=int(input("e= ")) #12
III: DATA.append(None)
IV: END
le=len(DATA)
print("Len:", le)
print("D:",DATA)
DATA[le-1]=e
print("Len:", le)
print("D:",DATA)

Page 2 of 22 EDUCATION FOR EVERYONE


DotPyEdu PLAY WITH PYTHON
IV: BEG
le=len(DATA)
print(DATA)
for i in range(le-1,0,-1):
DATA[i]=DATA[i-1]
DATA[0]=e
print("Len:", len(DATA))
print ("D:", DATA)
IV: POS
pos=int(input("pos= ")) #4
le=len(DATA)
for i in range(le-1,pos,-1):
DATA[i]=DATA[i-1]
DATA[pos]=e
print("Len:", len(DATA))
print ("D:", DATA)

IV: SORTED
D: [11, 22, 43, 44, 55, 61, 77]
e=int(input("e= ")) #47
DATA.append(None)
pos=0; le =len(DATA)
for i in range(le):
if DATA[i]>e:
pos=i; break
print("Pos:",pos)
for i in range(le-1,pos,-1):
DATA[i]=DATA[i-1]
DATA[pos]=e
print("Len:", len(DATA))
print ("D:", DATA)

Page 3 of 22 EDUCATION FOR EVERYONE


DotPyEdu PLAY WITH PYTHON
STACK (PUSH + POP)
APPLICATIONS OF STACK
Some of the applications of STACK in real-
life are:
1. Pile of clothes in an almirah
2. Multiple chairs in a vertical pile
3. Bangles worn on wrist
4. Pile of boxes of eatables in pantry or
on a kitchen shelf

OPERATIONS ON STACK
As explained in the previous section, a STACK is a mechanism that implements LIFO arrangement
hence elements are added and deleted from the STACK at one end only. The end from which
elements are added or deleted is called TOP
of the STACK. Two fundamental
operations performed on the STACK are
PUSH and POP. In this section, we will
learn about them and implement them using
Python. PUSH adds a new element at the
TOP of the STACK. It is an insertion
operation. We can add elements to a
STACK until it is full. A STACK is full when
no more elements can be added to it. Trying
to add an element to a full STACK results in
an exception called
‘overflow’.
POP operation is used to remove the top
most element of the STACK, that is, the
Page 4 of 22 EDUCATION FOR EVERYONE
DotPyEdu PLAY WITH PYTHON
element at the TOP of the STACK. It is a delete operation. We can delete elements from a STACK
until it is empty i.e. there is no element in it. Trying to delete an element from an empty STACK
results in an exception called ‘underflow’.

IMPLEMENTATION OF STACK IN PYTHON


 insert/delete elements (glasses)
 check if the STACK is empty (no glasses in the STACK)
 find the number of elements (glasses) in the STACK
 read the value of the topmost element (number on the topmost glass) in the STACK
The program shall define the following functions to perform these operations
• Let us create an empty STACK named element in STACK. This function has two
STACK. We will do so by assigning an empty parameters - the name of the STACK in which
list to the the element is to be inserted (STACK) and the
Identifier named STACK: element that needs to be inserted. We know
STACK = list() that insertion of an element is always done at
• A function named isEmpty to check whether the TOP of the STACK.
the STACK is empty or not. Remember trying shall use the built-in method append() of list to
to remove an element from an empty STACK add an element to the STACK that always adds
would result in ‘underflow’. This function at the end of the list.
returns True if the STACK is empty, else As there is no limit on the size of list in Python,
returns False. the implemented STACK will never be full
def isEmpty (STACK): unless there is no more space available in
if len(STACK) == 0: memory. Hence, we will never face ‘overflow’
return True (no space for new element) condition for
else: STACK.
return False def PUSH(STACK , element):
• A function named opPush to insert (PUSH) a STACK.append (element)
new
Page 5 of 22 EDUCATION FOR EVERYONE
DotPyEdu PLAY WITH PYTHON
• A function named size to read the number of for i in range(x-1,-1,-1): #from
elements in the STACK. We will use the len() Last(TOP)
function of list in Python to find the number of print(STACK[i])
elements in the STACK. • A function named opPop to delete the
def SIZE(STACK): topmost
return len(STACK) element from the STACK. It takes one
• A function named top to read the most recent parameter – the name of the STACK (STACK)
element (TOP) in the STACK. from which element is to be deleted and
def TOP(STACK): returns the value of the deleted element. The
if isEmpty(STACK): function first checks whether the STACK is
print('STACK is empty') empty or not. If it is not empty, it removes the
return None topmost element from it. We shall use the
else: builtin method pop() of Python list that
x =len(STACK) removes the
element= glassSt element from the end of the list.
• A function named display to show the def Pop (STACK):
contents of if isEmpty(STACK):
the STACK. print('underflow')
def DISPLAY(STACK): return None
x=len(STACK) else:
print("Current elements in the STACK return( STACK.pop() ) #del
are: ") STACK[len(STACK)-1]
ALL OPERATIONS ONE (1) TIMES

Page 6 of 22 EDUCATION FOR EVERYONE


DotPyEdu PLAY WITH PYTHON

STACK FOR SINGLE DATA (CODE)


#MAIN PROGRAM STARTS FROM HERE print("You selected to close this program")
x=[] def push(STACK , x): #function to add element at the
choice=0 end of list
while (choice!=4): STACK.append (x)
print("********STACK Menu***********") def pop(STACK): #function to remove last
print("1. push(INSERT)") element from list
print("2. pop(DELETE)") n = len(STACK)
print("3. Display ") if(n<=0):
print("4. Exit") print("STACK empty....Pop not possible")
choice = int(input("Enter your choice :")) else:
if(choice==1): STACK.pop()
value = int(input("Enter value ")) def display(STACK): #function to display STACK
push( x, value) entry
if(choice==2): if len(STACK)<=0:
pop(x) print("STACK empty...........Nothing to display")
if(choice==3): for i in STACK:
display(x) print(I , end=" ")
if(choice==4):
OUTPUT
********STACK Menu*********** Enter your choice :1
1. push(INSERT) Enter value 12
2. pop(DELETE) ********STACK Menu***********
3. Display 1. push(INSERT)
4. Exit 2. pop(DELETE)
Page 7 of 22 EDUCATION FOR EVERYONE
DotPyEdu PLAY WITH PYTHON
3. Display 1. push(INSERT)
4. Exit 2. pop(DELETE)
Enter your choice :1 3. Display
Enter value 5 4. Exit
********STACK Menu*********** Enter your choice :3
1. push(INSERT) 12 5 22 11
2. pop(DELETE) ********STACK Menu***********
3. Display 1. push(INSERT)
4. Exit 2. pop(DELETE)
Enter your choice :3 3. Display
12 5 4. Exit
*******STACK Menu*********** Enter your choice :2
1. push(INSERT) ********STACK Menu***********
2. pop(DELETE) 1. push(INSERT)
3. Display 2. pop(DELETE)
4. Exit 3. Display
Enter your choice :1 4. Exit
Enter value 22 Enter your choice :3
********STACK Menu*********** 12 5 22
1. push(INSERT) ********STACK Menu***********
2. pop(DELETE) 1. push(INSERT)
3. Display 2. pop(DELETE)
4. Exit 3. Display
Enter your choice :1 4. Exit
Enter value 11 Enter your choice :4
********STACK Menu*********** You selected to close this program

Page 8 of 22 EDUCATION FOR EVERYONE


DotPyEdu PLAY WITH PYTHON

MULTIPLE ITEMS IN PUSH OPERATION (CODE)


#MAIN PROGRAM STARTS FROM HERE display(x)
x=[] if(choice==4):
Item_name="" print("You selected to close this program")
Item_code=0 def push(STACK , x): #function to add element at the
choice=0 end of list
while (choice!=4): STACK.append (x)
print("********STACK Menu***********") def pop(STACK): #function to remove last element
print("1. push(INSERT)") from list
print("2. pop(DELETE)") n = len(STACK)
print("3. Display ") if(n<=0):
print("4. Exit") print("STACK empty....Pop not possible")
choice = int(input("Enter your choice")) else:
if(choice==1): STACK.pop()
Item_name=input("Enter Item_name= ") def display(STACK): #function to display STACK
Item_code=int(input("Enter Item_code= ")) entry
value=[Item_name,Item_code] if len(STACK)<=0:
push(x , value) print("STACK empty...........Nothing to display")
if(choice==2): for i in STACK:
pop(x) print(i , end=" ")
if(choice==3):
OUTPUT
********STACK Menu*********** 4. Exit
1. push(INSERT) Enter your choice:1
2. pop(DELETE) Enter Item_name= book1
3. Display Enter Item_code= 2009
Page 9 of 22 EDUCATION FOR EVERYONE
DotPyEdu PLAY WITH PYTHON
********STACK Menu*********** ['book1', 2009] ['c++', 3019] ['PYTHON', 2022]
1. push(INSERT) ********STACK Menu***********
2. pop(DELETE) 1. push(INSERT)
3. Display 2. pop(DELETE)
4. Exit 3. Display
Enter your choice:1 4. Exit
Enter Item_name= c++ Enter your choice:2
Enter Item_code= 3019 ********STACK Menu***********
********STACK Menu*********** 1. push(INSERT)
1. push(INSERT) 2. pop(DELETE)
2. pop(DELETE) 3. Display
3. Display 4. Exit
4. Exit Enter your choice:3
Enter your choice:1 ['book1', 2009] ['c++', 3019] ********STACK
Enter Item_name= PYTHON Menu***********
Enter Item_code= 2022 1. push(INSERT)
********STACK Menu*********** 2. pop(DELETE)
1. push(INSERT) 3. Display
2. pop(DELETE) 4. Exit
3. Display Enter your choice:4
4. Exit You selected to close this program
Enter your choice:3

1. Suppose STACK is allocated 6 memory denotes an empty location. Display the STACK S as
locations and initially STACK is empty (Top = the following operations
0). take place :
Give the output of the program segment : PUSH(S, Athens);
aaa = 2 bbb = 5 POP(S,ITEM);
push(STACK,aaa); POP(S,ITEM);
push(STACK,4); PUSH(S, Madrid);
push(STACK,bbb +2); PUSH(S, Moscow);
push(STACK,9); POP(S,ITEM);
push(STACK,aaa+bbb); Answer:
while Top > 0: 2. (i) London, Berlin, Rome, Paris, _______, _______.
pop(STACK,ITEM) (ii) PUSH(S, Athens)
print(ITEM) London, Berlin, Rome, Paris, Athens, _______.
Answer: (iii) POP(S, ITEM)
The output is : London, Berlin, Rome, Paris, _______, _______.
7 (iv) POP(S, ITEM)
9 London, Berlin, Rome, _______, _______, _______.
7 (v) PUSH(S, Madrid)
4 London, Berlin, Rome, Madrid, _______, _________.
2 (vi) PUSH(S, Moscow)
2. Consider the STACK S containing city names : London, Berlin, Rome, Madrid, Moscow, _________.
London, Berlin, Rome, Paris, ______, ______ (vii)POP(S, ITEM)
one name per location and where ______ London, Berlin, Rome, Madrid, _________,
_________.
Page 10 of 22 EDUCATION FOR EVERYONE
DotPyEdu PLAY WITH PYTHON

SAMPLE PAPER 2022


Q. 8: 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: 3 MM
● Push the keys (name of the student) of the dictionary into a stack, where the corresponding value (marks) is greater
than 75.
● Pop and display the content of the stack.
For example: Sample Pap
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"]
Solution:
# Question No 8 (first option)
R={"OM":76, "JAI":45, "BOB":89, "ALI":65, "ANU":90, "TOM":82}
def PUSH(S,N): for k in R:
S.append(N) if R[k]>=75:
def POP(S): PUSH( ST ,k)
if S!=[]: while True:
return S.pop() if ST!=[]:
else: print(POP(ST),end=" ")
return None else:
ST=[] break
OR
Alam 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 even numbers into a stack.
● Pop and display the content of the stack.
For Example:

Page 11 of 22 EDUCATION FOR EVERYONE


DotPyEdu PLAY WITH PYTHON
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
Solution: return None
# Question No 8 (second option) ST=[]
N=[12, 13, 34, 56, 21, 79, 98, 22, for k in N:
35, 38] if k%2==0:
def PUSH(S,N): PUSH(ST,k)
S.append(N) while True:
def POP(S): if ST!=[]:
if S!=[]: print(POP(ST),end=" ")
return S.pop() else:
else: break
Note: Marks to be awarded for any other correct logic given by the student
SAMPLE PAPER 2021
Q. 17: Write a function in python named PUSH (STACK, SET) where STACK is list of some numbers forming a stack and
SET is a list of some numbers. The function will push all the EVEN elements from the SET into a STACK implemented
by using a list. Display the stack after push operation.
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
Solution:
def PUSH(STACK,SET): STACK.append(i)
for i in SET: print("Updated Stack is : ",STACK)
if i%2==0:
OR
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.
Solution:
def POP(STACK):
if STACK==[]: #if len(STACK)==0 # if isEmpty(STACK)
print ("Stack is Empty")
else:
Print (STACK.pop ())
Note: Marks to BE AWARDED FOR ANY OTHER CORRECT LOGIC GIVEN BY THE STUDENT

QUESTIONS SET 1
Q 1. Write a function in python named PUSH (STACK, SET) where STACK is list of some numbers forming a stack
and SET is a list of some numbers. The function will push all the ODD elements from the SET into a STACK
implemented by using a list. Display the stack after push operation.
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: 13 21 79 35
Q 2. 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.
Q 3. Write push (rollno) and pop () method in python: Push (rollno) –add 5 roll number in Stack, pop ()- remove 2
roll number from Stack.

Page 12 of 22 EDUCATION FOR EVERYONE


DotPyEdu PLAY WITH PYTHON
Q 4. Write a function Push () which takes "name" as argument and add in a stack named "MyStack". After calling
push() three times, a message should be displayed "Stack is Full"
Q 5. Write PushBook (Book) & PopBook (Book) methods/functions in Python to add a new Book and delete a
Book from a List of Book titles, considering them to act as push and pop operations of the Stack data structure.
Q 6. Write a function in python, PushEl (element) to add a new element in List of element Description,
considering them to act as push operation of the Stack data structure.
Q 7. Write a function in python, PopEl (element) to delete an element from List of element Description,
considering them to act as pop operation of the Stack data structure
Q 8. Write a function 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.
Q 9. 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.
Q 10. 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.
Q 11. Write a function in Python STKPOP (STACK ), where Arr is a stack implemented by a list of numbers. The
function returns the value deleted from the stack.
Q 12. Write a function in Python PUSH(STACK , Arr), where Lst is a list of numbers. From this list push all numbers
not divisible by 6 into a stack implemented by using a list. Display the stack if it has at least one element, otherwise
display appropriate error message.
Q 13. Write a function in Python POP (Lst), where Lst is a stack implemented by a list of numbers. The function
returns the value deleted from the stack.
Q 14. A line of text is read from the input terminal into a stack. Write a program to output the string in the reverse
order, each character appearing twice.
Q 15. Write a function in Python Push (STACK , Arr ) to push any student’s information to stack, where Arr is a
stack implemented by a list of numbers. Format of student’s information is as follows: One student information is
a list of three elements i.e. his/her rollno, name and grade. Display the stack using display(stack),
Q 16. Write a function in Python code for Define pop ( ) function on a stack STK where the function returns the
deleted item.
Q 17. Write a function in Python SPUSH (st ,Arr), where Arr is a list of strings, from this list push all strings have
length more than 20, into a stack implemented by using a list. Display the stack using display(stack),
Q 18. 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.
Q 19. Write a function in Python PUSH (STACK, ITEM) to insert an element in the stack. After inserting the element
display the stack. To push an element into a stack
Q 20. Write a function in Python POP (STACK) to remove the element from the stack and also display the deleted
value. To pop an element from the stack
Q 21. Write a function in Python PUSH (STACK, Arr), where Arr is a list of numbers. From this list push all numbers
divisible by 5 and 3 into a stack implemented by using a list. Display the stack if it has at least one element,
otherwise display appropriate error message.
Q 22. Write a function in Python popStack (st), where Arr is a stack implemented by a list of numbers. The
function returns the value deleted from the stack.
Q 23. Write a function in Python POP_STACK (Arr), where Arr is a stack implemented by a list of numbers. The
function returns the value deleted from the stack. Also display a underflow message if the stack does not contain
any element.
Page 13 of 22 EDUCATION FOR EVERYONE
DotPyEdu PLAY WITH PYTHON
Q 24. 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.
Q 25. 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.
Q 26. 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.
Q 27. Write a function AddCustomer (Customer) in Python to add a new Customer information NAME into the List
of CStack and display the information.
Q 28. Write a function DeleteCustomer (CStack) to delete a Customer information from a list of CStack. The
function delete the name of customer from the stack.
SOLUTION SET 1
Q 1. Write a function in python named PUSH(STACK, Push (MyStack, rollno)
SET) where STACK is list of some numbers forming a POP(MyStack)
stack and SET is a list of some numbers. The POP(MyStack)
function will push all the EVEN elements from the Q 4. Write a function Push (MyStack, Names) which
SET into a STACK implemented by using a list. takes "name" as argument and add in a stack
Display the stack after push operation. named "MyStack". After calling push() three times,
def PUSH(STACK,SET): a message should be displayed "Stack is Full"
for i in SET: CODE 1:
if i%2==0: MyStack=[]
STACK.append(i) StackSize=3
print("Updated Stack is : ",STACK) def Push(MyStack, Names):
Q 2. Write a function in python named POP(STACK) if len(MyStack) < StackSize:
where STACK is a stack implemented by a list of MyStack.append(Value)
numbers. The function will display the popped else:
element after function call. print("Stack is full!")
def POP(STACK): CODE 2:
if STACK==[]: #if len(STACK)==0 #if not a: def Push(MyStack, Names):
print("Stack is Empty") MyStack.append(Names)
else: MyStack=[]
print(STACK.pop()) StackSize=3
Q 3. Write push(rollno) and pop() method in python: whiel 1:
push(rollno) --add 5 roll number in Stack, pop() -- Names =int(input("Enter Names. : "))
- remove 2 roll number from Stack. if len(MyStack) < StackSize:
MyStack=[] Push (MyStack, Names)
def Push(MyStack ,rollno): else: print("Stack is full!")
MyStack.append(rollno) Q 5. Write PushBook(Book) and PopBook(Book)
def POP(MyStack): methods/functions in Python to add a new Book
if len(MyStack) > 0: and delete a Book from a List of Book titles,
MyStack.pop() considering them to act as push and pop operations
else: of the Stack data structure.
print("Stack is empty.") def PushBook(Book):
MyStack=[] bno = input("enter book no : ")
for I in range(5): btitle = input(“enter book title:”)
rollno =int(input("Enter Roll. No. : ")) rec = bno + " " + btitle
Page 14 of 22 EDUCATION FOR EVERYONE
DotPyEdu PLAY WITH PYTHON
Book.append(rec) STACK=[]
print(Book) def PUSH(STACK ,ARR):
OR for x in ARR:
def PopBook(Book) : if x%5==0:
if len(Book)==0: # if isEmpty. Stack #if not a: STACK.append(x)
print ("Underflow") def POP(STACK):
else: if len(STACK)==0:
print (“Deleted entry:”, Book.pop()) print("Empty Stack")
Q 6. Write a function in python, PushEl (element) to else:
add a new element in List of element Description, print(s)
considering them to act as push operation of the Q 10. Write a function in Python POP (STACK), where
Stack data structure. Arr is a stack implemented by a list of numbers. The
def PushEl(element): function returns the value deleted from the stack.
a=int (input ("enter package title: ")) def POP(STACK) :
element.append(a) if len(st)==0: # if isEmpty.Stack #if not Stack:
Q 7. Write a function in python, PopEl (Stack) to delete print("Underflow")
an element from List of element Description, else:
considering them to act as pop operation of the return STACK.pop()
Stack data structure. Q 11. Write a function in Python STKPOP (STACK ),
def PopEl(Stack): where Arr is a stack implemented by a list of
if Stack ==[]: # if isEmpty. Stack #if not numbers. The function returns the value deleted
Stack: from the stack.
print( "Stack empty") def STKPOP(STACK):
else: if len(STACK)==0: # if isEmpty.Stack #if not Stack:
print ("Deleted element:", print("Underflow")
Stack.pop()) else:
Q 8. Write a function in python, MakePush (Package) return STACK.pop()
and MakePop (Package) to add a new Package and Q 12. Write a function in Python PUSH (STACK , Arr),
delete a Package from a List of Package Description, where Lst is a list of numbers. From this list push all
considering them to act as push and pop operations numbers not divisible by 6 into a stack implemented
of the Stack data structure. by using a list. Display the stack if it has at least one
def MakePush(Package): element, otherwise display appropriate error
a=int(input("enter package title : ")) message.
Package.append (a) def PUSH (STACK , Arr,):
def MakePop(Package): s=[]
if (Package==[]): for x in range (0, len(Arr)):
print( "Stack empty") if Arr[x] % 6 ! = 0:
else: STACK.append (Arr[x])
print ("Deleted element:", Package.pop ()) def DIS (STACK):
Q 9. Write a function in Python PUSH (STACK, ARR), if len (STACK) = = 0:
where Arr is a list of numbers. From this list push all print(“Empty Stack”)
numbers divisible by 5 into a stack implemented by else:
using a list. Display the stack if it has at least one print (STACK)
element, otherwise display appropriate error
message.
Page 15 of 22 EDUCATION FOR EVERYONE
DotPyEdu PLAY WITH PYTHON
Q 13. Write a function in Python POP(Lst), where Lst is a DISPLAY (STACK)
stack implemented by a list of numbers. The Q 16. Define POP (STACK) function on a stack STACK
function returns the value deleted from the stack. where the function returns the deleted item.
def STKPOP(STACK): def POP(STACK):
if len(STACK)==0: # if isEmpty.Stack #if not Stack: if len(STACK)==0: # if isEmpty.Stack #if not Stack:
print("Underflow") print("Underflow")
else: else:
return STACK.pop() return STACK.pop()
Q 14. A line of text is read from the input terminal into a Q 17. Write a function in Python ADD (STACK ,ARR),
stack. Write a program to output the string in the where Arr is a list of strings, From this list push all
reverse order, each character appearing twice. strings have higher length than 20 , into a stack
S = input ( “ Enter a string : “ ) implemented by using a list. Display the stack.
Stack = [ ] STACK =[ ]
def PUSH (STACK , S): def ADD(STACK ,ARR):
for I in S : for s in ARR:
Stack.append ( I ) if len(s)> 20:
L = len ( Stack ) STACK.append(s).
def DIS (STACK): print( STACK )
if len (STACK) = = 0: Q 18. Write a function in Python POP (ARR), where Arr
print("Underflow") is a stack implemented by a list of numbers. The
else: function returns the value deleted from the stack.
for I in range ( L ) : def POP ( ARR ):
print (Stack[I] * 2 , end = “ ”) if len(ARR) == 0:
Q 15. Write a function in Python Push (STACK , Arr ) to print( 'StackEmpty').
push any student’s information to stack, where Arr return -1
is a stack implemented by a list of numbers. Format else:
of student’s information is as follows: One student return ARR.pop()
information is a list of three elements i.e. his/her Q 19. Write a function in Python PUSH () to insert an
rollno, name and grade. element in the stack. After inserting the element display
STACK =VAL= [ ] the stack. To push an element into a stack
def push (STACK, VAL ): # SAME AS QUESTION 12
STACK.append (VAL) Q 20. Write a function in Python POP() to remove the
def DISPLAY (STACK ): element from the stack and also display the deleted
if len (STACK) = = 0: value. To pop an element from the stack
print("Underflow") # SAME AS QUESTION 16
else: Q 21. Write a function in Python PUSH(ARR, VALUE),
for I in range ( L ) : where Arr is a list of numbers. From this list push all
print (Stack[I]) numbers divisible by 5 and 3 into a stack
N = input ( " Enter the number of students " ) implemented by using a list. Display the stack if it
for i in range ( N ) : has at least one element, otherwise display
ROLLNO =int( input ( " Enter student rollno? " ) ) appropriate error message.
NAME = input ( " Enter student name " ) ) STACK =[]
GRADE =input ( " Enter student grade " ) ) def PUSH(ARR, VALUE):
VAL.append ([ROLLNO, NAME , GRADE]) for x in range(0,len(Arr)):
PUSH (STACK, VAL)
Page 16 of 22 EDUCATION FOR EVERYONE
DotPyEdu PLAY WITH PYTHON
if Arr[x]%5==0 and Arr[x]%3==0: if len(STACK)==0:

STACK.append(Arr[x]) print("Empty Stack")


def DISPLAY(STACK): else: print(STACK)
if len(STACK)==0: Q 25. Write a function in Python POP(cities), where
cities is a stack implemented by a list of city names
print("Empty Stack") for eg. cities=[‘Delhi’, ’Jaipur’, ‘Mumbai’, ‘Nagpur’].
else: print(STACK) The function returns the value deleted from the
Q 22. Write a function in Python popStack(st) , where stack.
Arr is a stack implemented by a list of numbers. The # SAME AS QUESTION 12
function returns the value deleted from the stack. Q 26. Write a function POP(Book) in Python to delete a
# SAME AS QUESTION 16 Book from a list of Book titles, considering it to act
Q 23. Write a function in Python POP_STACK(Arr), as a pop operation of the Stack data structure.
where Arr is a stack implemented by a list of # SAME AS QUESTION 16
numbers. The function returns the value deleted Q 27. Write a function ADDCUSTOMER (CSTACK ,
from the stack. Also display a underflow message if CUSTOMER) in Python to add a new Customer
the stack does not contain any element. information NAME into the List of CStack and
# SAME AS QUESTION 16 display the information.
Q 24. Write a function in Python PUSH(Num), where def ADDCUSTOMER(CSTACK ,CUSTOMER):
Num is a list of integer numbers. From this list push CSTAKE.append (CUSTOMER)
all positive even numbers into a stack implemented def DISPLAY(CSTACK):
by using a list. Display the stack if it has at least one if len(CSTACK)==0:
element, otherwise display appropriate error print (“Empty Stack”)
message. else:
STACK =[] print (CSTACK)
def PUSH(NUM): Q 28. Write a function DeleteCustomer() to delete a
for x in NUM: Customer information from a list of CStack. The
if x%2==0 and x>0: function delete the name of customer from the
STACK.append(x) stack.
def POP(S): def DELETECUSTOMER(CSTACK):
if len(STACK)==0: if CSTACK ==[]:
print("STACK EMPTY") print(“There is no Customer!”)
else: else:
print(STACK) return CSTACK.pop()
def DISPLAY(STACK):

QUESTIONS SET 2
Q 1. Write a function in python named PUSH (STACK, ITEMS) where STACK is list of some +VE numbers forming a
stack and ITEMS is a list value as numbers. The function will push all the +ve elements into STACK implemented by
PUSH operation. Display the stack after push operation.
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]

Page 17 of 22 EDUCATION FOR EVERYONE


DotPyEdu PLAY WITH PYTHON
Q 2. Write a function in python named PUSH (STACK, ITEMS) where STACK is list of some –VE numbers forming a
stack and ITEMS is a list value as numbers. The function will push all the -ve elements into STACK implemented by
PUSH operation. Display the stack after push operation.
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: [-13,-21,-79,-35]
Q 3. Write a function in python named PUSHZeroEnding (STACK, ITEMS) where STACK is list of some numbers ended
by 0 forming a stack and ITEMS is a list value as numbers. The function will push all the numbers ended by 0 into
STACK implemented by PUSH operation. Display the stack after push operation.
For Example:
If the sample Content of the list is as follows: N= [10, 13, 30, 40, -21, -79, 70, 20, -35, 80]
Sample Output of the code should be: [10, 13, 30, 40, 20, 80]
Q 4. Alam 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: [13, 21, 79, 35]
Q 5. Write a function PUSH AddCustomerNames (Stack, Customer_Name) in Python to add a new Customer Name
from Customer_Name_List which are starting with alphabet 'a' or 'A'.
For Example: If the sample Content of the list is as follows:
Customer_Name_List =[ 'Aman','Raman','Suman','Chaman','Amit','Ankur']
Sample Output of the code should be: ['Aman','Amit','Ankur']
Q 6. Write a function PUSH AddCityNames (Stack, City_Name_List) in Python to add a new City Name from
City_Name_List which are starting with alphabet 'M'.
For Example:
If the sample Content of the list is as follows:
City_Name_List =['Mumbai','Delhi','Bangalore','Ahmedabad','Meerut','Madurai','Kolkata']
Sample Output of the code should be: ['Mumbai', 'Meerut', 'Madurai']
Q 7. Write a function PUSH AddStatesNames (Stack, States_Name_List) in Python to add a new States Name from
States_Name_List which are starting with alphabet 'T' or 'O'.
For Example: If the sample Content of the list is as follows:
States_Name_List = ['Punjab', 'Delhi', 'Uttar Pradesh','Karnataka', 'Telangana','Tamil Nadu','Odisha']
Sample Output of the code should be: ['Telangana', 'Tamil Nadu', 'Odisha']
Q 8. Write a function PUSH AddBookNames (Stack, Books_Name_List) in Python to add a new Book Name from
Books_Name_List, where Book names Length less than 10.
For Example: If the sample Content of the list is as follows:
Books_Name_List =
['Lost Time' , 'Ulysses' , 'Don Quixote' , , 'The Great Gatsby', 'Madame Bovary', 'Moby Dick' ,'War and Peace' ]
Sample Output of the code should be: ['Lost Time ' , 'Ulysses ' , 'Moby Dick']

Q 9. Write a function PUSH AddBookNames (Stack, Book_Name_List) in Python to add a new Book Name from
Books_Name_List , where Book names Length more than 10.
For Example: If the sample Content of the list is as follows:
Books_Name_List = ['Lost Time' , 'Ulysses' , 'Don Quixote' , 'The Great Gatsby', 'Madame Bovary', 'Moby Dick'
,'War and Peace' ]
Sample Output of the code should be:

Page 18 of 22 EDUCATION FOR EVERYONE


DotPyEdu PLAY WITH PYTHON
['Don Quixote', 'The Great Gatsby', 'Madame Bovary', 'War and Peace']
Q 10. Reena 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:
● Push the Values (marks of the student) of the dictionary into a stack, where the corresponding value (marks) is
greater than 75.
● Pop and display the content of the stack.
For example: Sample Pap
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: [76, 89, 90, 82]
Q 11. Write PushBook (Book, R) and PopBook (Book) methods/functions in Python to add Btitle have character size
4 only in Stack Book from R is a Book with BNo and Btitle and delete a Book from a List of Book List by BNo,
considering them to act as push and pop operations of the Stack data structure.
For example: Book,
If the sample content of the dictionary is as follows: R={3240:"C++",4051: "Python",1089: "JAVA",65: "HTML":90,
9801:"PHP",1010:"PHP+"}
The output from the program should be: ["HTML", "PHP+"]
SOLUTION SET 2
Q 1. Write a function in python named PUSH (STACK, ITEMS) where STACK is list of some +VE numbers forming a
stack and ITEMS is a list value as numbers. The function will push all the +VE elements into STACK implemented
by PUSH operation. Display the stack after push operation.
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]
def PUSH(STACK, ITEMS):
for i in ITEMS:
if i>0:
STACK.append(i)
def DISPLAY(STACK):
if len(STACK)==0:
print("Empty Stack")
else:
print(STACK)
Q 2. Write a function in python named PUSH (STACK, ITEMS) where STACK is list of some –VE numbers forming a
stack and ITEMS is a list value as numbers. The function will push all the -ve elements into STACK implemented
by PUSH operation. Display the stack after push operation.
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: [-13,-21,-79,-35]
def PUSH(STACK, ITEMS):
for i in ITEMS:
if i<0:
STACK.append(i)
def DISPLAY(STACK):
if len(STACK)==0:
print("Empty Stack")
else:
print(STACK)
Page 19 of 22 EDUCATION FOR EVERYONE
DotPyEdu PLAY WITH PYTHON
Q 3. Write a function in python named PUSHZeroEnding (STACK, ITEMS) where STACK is list of some numbers
ended by 0 forming a stack and ITEMS is a list value as numbers. The function will push all the numbers ended
by 0 into STACK implemented by PUSH operation. Display the stack after push operation.
For Example:
If the sample Content of the list is as follows: N= [10, 13, 30, 40, -21, -79, 70, 20, -35, 80]
Sample Output of the code should be: [10, 13, 30, 40, 20, 80]
def PUSH(STACK, ITEMS):
for i in ITEMS:
if i%10==0:
STACK.append(i)
def DISPLAY(STACK):
if len(STACK)==0:
print("Empty Stack")
else:
print(STACK)
Q 4. Alam 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: [13, 21, 79, 35]
def PUSH(STACK, ITEMS):
for i in ITEMS:
if i%2!=0: # i%2==1:
STACK.append(i)
def DISPLAY(STACK):
if len(STACK)==0:
print("Empty Stack")
else:
print(STACK)
Q 5. Write a function PUSH AddCustomerNames (Stack, Customer_Name_List) in Python to add a new Customer
Name from Customer_Name_List which are starting with alphabet 'a' or 'A'.
For Example: If the sample Content of the list is as follows:
Customer_Name_List =[ 'Aman','Raman','Suman','Chaman','Amit','Ankur']
Sample Output of the code should be: ['Aman','Amit','Ankur']
def PUSH AddCustomerNames (STACK, Customer_Name):
for s in Customer_Name_List:
if s[0] in 'aA':
STACK.append(s)
def DISPLAY(STACK):
if len(STACK)==0:
print("Empty Stack")
else:
print(STACK)
Q 6. Write a function PUSH AddCityNames (Stack, City_Name_List) in Python to add a new City Name from
City_Name_List which are starting with alphabet 'M'.
For Example:
Page 20 of 22 EDUCATION FOR EVERYONE
DotPyEdu PLAY WITH PYTHON
If the sample Content of the list is as follows:
City_Name_List =['Mumbai','Delhi','Bangalore','Ahmedabad','Meerut','Madurai','Kolkata']
Sample Output of the code should be: ['Mumbai', 'Meerut', 'Madurai']
def PUSH AddCityNames (STACK, City_Name_List):
for s in Customer_Name_List:
if s[0] == 'M':
STACK.append(s)
def DISPLAY(STACK):
if len(STACK)==0:
print("Empty Stack")
else:
print(STACK)
Q 7. Write a function PUSH AddStatesNames (Stack, States_Name_List) in Python to add a new States Name from
States_Name_List which are starting with alphabet 'T' or 'O'.
For Example: If the sample Content of the list is as follows:
States_Name_List = ['Punjab', 'Delhi', 'Uttar Pradesh','Karnataka', 'Telangana','Tamil Nadu','Odisha']
Sample Output of the code should be: ['Telangana', 'Tamil Nadu', 'Odisha']
def PUSH Add States Names (STACK, States_Name_List):
for s in States_Name_List:
if s[0] == 'T' and s[0] == 'o' :
STACK.append(s)
def DISPLAY(STACK):
if len(STACK)==0:
print("Empty Stack")
else:
print(STACK)

Q 8. Write a function PUSH AddBookNames (Stack, Books_Name_List) in Python to add a new Book Name from
Books_Name_List, where Book names Length less than 10.
For Example: If the sample Content of the list is as follows:
Books_Name_List =
['Lost Time' , 'Ulysses' , 'Don Quixote' , , 'The Great Gatsby', 'Madame Bovary', 'Moby Dick' ,'War and Peace' ]
Sample Output of the code should be: ['Lost Time ' , 'Ulysses ' , 'Moby Dick']
def PUSH AddBookNames (STACK, Book_Name_List):
for s in Book_Name_List:
if len(s) <10 :
STACK.append(s)
def DISPLAY(STACK):
if len(STACK)==0:
print("Empty Stack")
else:
print(STACK)
Q 9. Write a function PUSH AddBookNames (Stack, Book_Name_List) in Python to add a new Book Name from
Books_Name_List , where Book names Length more than 10.
For Example: If the sample Content of the list is as follows:
Books_Name_List = ['Lost Time' , 'Ulysses' , 'Don Quixote' , 'The Great Gatsby', 'Madame Bovary', 'Moby Dick'
,'War and Peace' ]
Sample Output of the code should be:
Page 21 of 22 EDUCATION FOR EVERYONE
DotPyEdu PLAY WITH PYTHON
['Don Quixote', 'The Great Gatsby', 'Madame Bovary', 'War and Peace']
def PUSH AddBookNames (STACK, Book_Name_List):
for s in Book_Name_List:
if len(s) >10 :
STACK.append(s)
def DISPLAY(STACK):
if len(STACK)==0:
print("Empty Stack")
else:
print(STACK)
Q 10. Reena 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:
● Push the Values (marks of the student) of the dictionary into a stack, where the corresponding value (marks) is
greater than 75.
● Pop and display the content of the stack.
For example: Sample Pap
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: [76, 89, 90, 82]
def PUSH(STACK, R):
for k in R.keys():
if R[k] >=75:
S.append(R[k])
def DISPLAY(STACK):
if len(STACK)==0:
print("Empty Stack")
else:
print(STACK)

Q 11. Write PushBook (Book, R) and PopBook (Book) methods/functions in Python to add Btitle have character size
4 only in Stack Book from R is a Book with BNo and Btitle and delete a Book from a List of Book List by BNo,
considering them to act as push and pop operations of the Stack data structure.
For example: Book,
If the sample content of the dictionary is as follows: R={3240:"C++",4051: "Python",1089: "JAVA",65: "HTML":90,
9801:"PHP",1010:"PHP+"}
The output from the program should be: ["HTML", "PHP+"]
def PUSH(Book, R):
for k in R.keys():
n=R[k]
if len(n)==4:
S.append(R[k])
def DISPLAY(STACK):
if len(STACK)==0:
print("Empty Stack")
else:
print(STACK)

Page 22 of 22 EDUCATION FOR EVERYONE

You might also like