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

Stack Notes Programs

Uploaded by

vidyuthno1
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Stack Notes Programs

Uploaded by

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

Stack Implementation Programs:

1. Write a function in Python, MakePush(Package) and Make Pip(Package), to


add a new Package anddelete a Package from a List of Package Description,
considering them to act as push and pop operations of the Stack data structure.
def MakePush (Package):
a = int (input ("enter package title:"))
Package.append(a)
def MakeUp (Package) :
if (Package== []):
print ("Stack empty")
else:
print ("Deleted element:",Package.pop ())

2. Consider the following similar codes (carefully go through these) and predict
their outputs.
NList = [60, 32, 13, 'hello' ] NList = [ 60, 32, 13, 'hello']
print (NList[1], NList[-2]) print (NList[1], NList[-2])
NList.append( 15 ) NList.append( 15 )
print(len (NList)) print(len (NList) )
print( len(NList[3])) print(len (NList[3]))
NList.pop(3) NList.pop(3)
NList.sort() NList.insert (2, [14, 15])
NList.insert(2, [14, 15]) NList[3] += NList[4]
NList[3] += NList[4] NList[3] += NList[2][1]
NList[3] += NList[2][1] print (NList[3])
print (NList[3]) NList[2].remove (14)
NList.pop() print (NList)
NList[2].remove(14)
print (NList)
Output :- Output :-
32 13 32 13
5 5
5 5
107 43
[13, 15, [15], 107] [60, 32, [15], 43, 15]
3. What will be the output produced by following code ?
text = ['h', 'e', 'l', 'l', 'o']
print (text)
vowels = "aeiou"
newText = [x.upper() for x in text if x not in vowels ]
print (newText)
Output:-
['h', 'e', 'l', 'l', 'o']
['H', 'L', 'L']

4. Write a program that depending upon user's choice, either pushes or pops an
element in a stack .
stack = [ ]
while True :
com = input("Enter ( Push or Pop ) : ")
if com == "push" or com == "Push" :
num = int(input("Enter a number : "))
stack.append(num)
elif len(stack) == 0 :
print("Underflow")
elif com == "pop" or com == "Pop" :
stack.pop()
yes = input ("Enter ( Yes or no ) : ")
if yes == "No" or yes == "no":
print("Thank you !!!!")
break
print(stack)

5. A line of text is read from the input terminal into a stack. Write a program to
output the string in reverse order, each character appearing twice. (e.g., the
string a b c d e should be changed to ee dd cc bb aa)

line = input("Enter a line : ")


stack = [ ]
for i in line :
stack.append(i+i)
stack.reverse()
for j in stack :
print( j , end=" ")
6.Write a function in Python POP(Arr), where Arr is a stack implemented by a
list of numbers. The function returns the value deleted from the stack.

def POP(Arr):
Arr.pop()
return Arr

stack = [ ]
while True :
print()
print("Enter your choice as per given -")
print("1 = For insert data Enter insert ")
print("2 = For delete data enter delete ")
print("3 = For Exit enter exit ")
print()
user = input("Enter your choice :- ")
if user == "insert" :
num = int(input("Enter a number :- "))
stack.append(num)
elif user == "delete" :
if stack == [ ]:
print("UnderFlow")
else :
stack = POP(stack)
else :
break
print("Now our stack = ",stack)

7. Each node of a STACK contains the following information :


(i) Pin code of a city, (ii) Name of city
Write a program to implement following operations in above stack
(a) PUSH () To push a node in to the stack.
(b) POP( ) To remove a rode from the stack.
stack = [ ]
while True :
print()
print("Enter your choice as per given -")
print("1 = For insert data Enter insert ")
print("2 = For delete data enter delete ")
print("3 = For Exit enter exit ")
print()
user = input("Enter your choice :- ")
if user == "insert" :
pin = int(input("Enter the pin code of city :- "))
city = input("Enter name of city :- ")
data = [ pin , city ]
stack.append(data)
elif user == "delete" :
if stack == [ ]:
print("Under Flow")
else :
stack.pop()
else :
break
print("Now our stack = ",stack)

8. Write PUSH (Books) and POP (Books) methods, in python to add Books and
remove book considering them to act as Push and Pop operations of Stack.
def POP(Books):
Books.pop()
return Books

def Push (Book):


stack.append(Book)

stack = [ ]
while True :
print()
print("Enter your choice as per given -")
print("1 = For insert data Enter insert ")
print("2 = For delete data enter delete ")
print("3 = For Exit enter exit ")
print()
user = input("Enter your choice :- ")
if user == "insert" :
Book = input("Enter name of Book :- ")
Push (Book)
elif user == "delete" :
if stack == [ ]:
print("UnderFlow")
else :
stack = POP(stack)
else :
break
print("Now our stack = ",stack)

9.

Ans:
10.

Ans:

11. 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: The output should be:

['Naypyidaw', 'Myanmar'], ['Columbo', 'Sri Lanka']


['Dubai', 'UAE'], ['Dubai', 'UAE']
['Columbo', 'Sri Lanka'] ['Naypyidaw', 'Myanmar']
Stack empty
Ans:
travel= []
def Push_element (NList):
for L in NList: if L[1] != "India" and L[2]<3500:
travel.append([L[0],L[1]])
def Pop element ():
while len (travel):
print (travel.pop())
else:
print ("Stack Empty")

12. A list contains following record of a customer: [Customer_name,


Phone_number, City] Write the following user defined functions to perform
given operations on the stack named ‘status’:
(i) Push_element() - To Push an object containing name and Phone number of
customers who live in Goa to the stack.
(ii) Pop_element() - To Pop the objects from the stack and display them. Also,
display “Stack Empty” when there are no elements in the stack.

For example: If the lists of customer details are:


Ans:
13. Write a function in Python, Push(SItem) where , SItem is a dictionary
containing the details of stationary items– {Sname:price}.The function should
push the names of those items in the stack who have price greater than 75. Also
display the count of elements pushed into the stack.

For example: If the dictionary contains the following data:


Ditem={"Pen":106,"Pencil":59,"Notebook":80,"Eraser":25}
The stack should contain Notebook Pen. The output should be:The count of
elements in the stack is 2
Ans:

14. 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”.
NoVowel=[]
def PushNV(N):
for i in range(len(N)):
if 'A' in N[i] or 'E' in N[i] or 'I' in N[i] or 'O' in N[i] or 'U' in N[i]:
pass
else:
NoVowel.append(N[i])

All=[]
for i in range(5):
w=input("Enter Words:")
All.append(w)

PushNV(All)
while True:
if len(NoVowel)==0:
print("EmptyStack")
break
else:
print(NoVowel.pop()," ",end='')

15. 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 of
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, 301
Then the stack Only3 _5 should store
[10, 6, 18, 30]
And the output should be displayed as
30 18 10 StackEmpty

ANS:
Only3_5=[]
def Push3_5(N):
for i in N:
if i %3==0 or i%5==0:
Only3_5.append(i)

NUM=[]
for i in range(5):
n=int(input("Enter the number to add to list:"))
NUM.append(n)

Push3_5(NUM)
print("List of Only 3-5:",Only3_5)
while True:
if Only3_5==[]:
print("StackEmpty")
break
else:
print(Only3_5.pop()," ",end='')
16.Write a function to push any student’s information to stack.
def push(stack):
s=[]
print “STACK BEFORE PUSH”
display(stack)
s.append(input(“Enter student rollno?”))
s.append(input(“Enter student name”))
s.append(input(“Enter student grade”))
stack.append(s)

def display (stack):


l=len(stack)
print “STACK CONTENTS”
for i in range(l-1,-1,-1):
print stack[i]
stack=[]
print “Creating Stack”
n = input(“Enter the number of students”)
for i in range(n):
push(stack)
display(stack)

17. Write a function in Python POP(Arr), where Arr is a stack implemented by a


list of numbers. The function returns the value deleted from the stack.

def POP(Arr):
Arr.pop()
return Arr

stack = [ ]
while True :
print()
print("Enter your choice as per given -")
print("1 = For insert data Enter insert ")
print("2 = For delete data enter delete ")
print("3 = For Exit enter exit ")
print()
user = input("Enter your choice :- ")
if user == "insert" :
num = int(input("Enter a number :- "))
stack.append(num)
elif user == "delete" :
if stack == [ ]:
print("UnderFlow")
else :
stack = POP(stack)
else :
break
print("Now our stack = ",stack)

18. The stack is left empty. Each character in the string is pushed to the stack
one at a time. Each character from the stack is individually removed and added
back to the string.
def createStack():
stack = []
return stack

def size(stack):
return len(stack)

def isEmpty(stack):
if size(stack) == 0:
return true

def push(stack, item):


stack.append(item)

def pop(stack):
if isEmpty(stack):
return
return stack.pop()

def reverse(string):
n = len(string)
stack = createStack()
for i in range(0, n, 1):
push(stack, string[i])
string = ""
for i in range(0, n, 1):
string += pop(stack)
return string

s = "PrepBytes"
print("The original string is : ", end="")
print(s)
print("The reversed string using stack is : ", end="")
print(reverse(s))

19. 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:
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]
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
20. Write a program that checks whether an input string is a palindrome or not
using stack. Write two functions.
(i) pushstr() (ii) popstr()

Book Back Questions:

Q1. Write a program that depending upon user's choice, either pushes or pops an element
in a stack .

Q10. Write PUSH (Books) and POP (Books) methods, in python to add Books and remove book
considering them to act as Push and Pop operations of Stack.

Q8. Each node of a STACK contains the following information :

(1) Pin code of a city,

(ii) Name of city

Write a program to implement following operations in above stack

(a) PUSH () To push a node in to the stack.

(b) POP( ) To remove a rode from the stack.

Q4. Write a program that depending upon user's choice, either pushes or pops an element
in a stack the elements are shifted towards right so that top always remains at 0th (zero)
index.

Q3. 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.
A line of text is read from the input terminal into a stack. Write a program to output the
string in reverse order, each character appearing twice. (e.g., the string a b c d e should be
changed to ee dd cc bb aa)

You might also like