Stack
Stack
Data + Structure
Data Structure is a way of collecting and organizing data in such a way that we can
perform operations on these data in an effective way.
Stack
** Stack is a linear data structure.
It is a user-defined or non-primitive data structure.
A stack is a data structure whose elements are accessed according to the Last-In
First-Out (LIFO) principle. This is because in a stack, insertion and deletion of
elements can only take place at one end, called top of the stack.
PUSH
POP
Implementing stack using list
Push operation: It means inserting element at the top of the stack. This can be done
with the help of append() method of the list as: st.append(element) where ‘st’ is a
list.
Pop operation: It means removing the topmost element from the stack. This can be
performed using pop() method of the list as: st.pop() where ‘st’ is a list. This method
returns the removed element that can be displayed.
** Pushing an element into stack already having five elements and stack size of 5,
then it is stack overflow. This condition is applicable to static stack.
** In a stack if user tries to remove element from empty stack it is stack underflow.
Give any two characteristics of stacks
Characteristics of Stacks:
It is a LIFO data structure
The insertion and deletion happens at one end i.e. from the top of the stack
Applications of Stack
Recursion
Reversing a string
Undo mechanism in text editors
Programs:
Source Code:
# Implementation of stack using list
st=[] #to create an empty list
def stkpush():
n=int(input("Enter a No. : "))
st.append(n)
def stkpop():
if st==[]: # if len(st)==0:
print("Stack Underflow/Stack is Empty")
else:
print(st.pop()," removed")
def display():
if st==[ ]:
print("Stack Underflow/Stack is empty")
else:
print("STACK CONTENTS: ")
L=len(st)-1
for i in range(L,-1,-1):
print(st[i])
while True:
print('***STACK DEMONSTRATION***')
print('***1. PUSH***')
print('***2. POP***')
print('***3. DISPLAY***')
choice=int(input('Enter your choice (1-3) to continue and other than (1-3) to
Exit'))
if choice==1:
stkpush()
elif choice==2:
stkpop()
elif choice==3:
display()
else:
print('Wrong choice')
break
2. Write a Python program to display unique vowels and the total number of
unique vowels present in the given word using Stack (implemented as list).
Source Code:
vowels=['a','e','i','o','u']
word=input('Enter the word to search for vowels:')
Stack=[]
for letter in word.lower():
if letter in vowels:
if letter not in Stack:
Stack.append(letter)
print(Stack)
print('The total number of unique vowels present in',word,'are',len(Stack))
3. 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:
● 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:
If the sample content of the dictionary is as follows:
R={"OM":76, "JAI":45, "BOB":89, "ALI":65, "ANU":90, "TOM":82}
OM BOB ANU TOM
Code:
R={"OM":76, "JAI":45, "BOB":89, "ALI":65, "ANU":90, "TOM":82}
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
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 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]
def POP(S):
if S!=[]:
return S.pop()
else:
return None
ST=[]
for k in N:
if k%7==0:
PUSH(ST,k)
while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break
5. 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.
st=[]
def PUSH(Arr):
for i in Arr:
if i%5==0:
st.append(i)
if len(st)==0:
print("Stack is Empty")
else:
for i in range(len(st)-1,1,-1):
print(st[i])
6. Write a function in Python, Addnew(Book) and Remove(Book), 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.
Code:
Book=[]
def Addnew(Book):
Bookname=input(‘Enter book name’)
Book.append(Bookname)
def Remove(Book):
if Book==[]:
print(‘Stack Underflow/ No Book Available’)
else:
print(‘Deleted book is:’,Book.pop())
Code:
Package=[]
def MakePush(Package):
Packagename=input(‘Enter package name’)
Package.append(Packagename)
def MakePop(Package):
if Package==[]:
print(‘Stack Underflow/No Package Available’)
else:
print(‘Delted package is:’,Package.pop())
For example:
If the lists of customer details are:
[“Gurdas”, “99999999999”,”Goa”]
[“Julee”, “8888888888”,”Mumbai”]
[“Murugan”,”77777777777”,”Cochin”]
[“Ashmit”, “1010101010”,”Goa”]
The stack should contain
[“Ashmit”,”1010101010”]
[“Gurdas”,”9999999999”]
Code:
status=[]
def Push_element(cust):
if cust[2]=="Goa":
L1=[cust[0],cust[1]]
status.append(L1)
For example:
If the dictionary contains the following data:
Ditem={"Pen":106,"Pencil":59,"Notebook":80,"Eraser":25}
Code:
stackItem=[]
def Push(SItem):
count=0
for k in SItem:
if (SItem[k]>=75):
stackItem.append(k)
count=count+1
print("The count of elements in the stack is : ", count)
10.
Code:
Only3_5=[]
def Push3_5(N):
for i in N:
if i%3==0 or i%5==0:
Only3_5.append(i)
Num=[]
i=1
while i<=5:
n=int(input('Enter a number'))
Num.append(n)
i+=1
Push3_5(Num)
while len(Only3_5)!=0:
print(Only3_5.pop(),end=' ')
else:
print("stack is Empty")