You are on page 1of 4

Velammal Vidyalaya

Practical Programs-Term2
Class XII-Computer Science
2022-2023

Program 1:

Aim: To write a program to show the implementation of stack using lists.

Program Code:

#implementation of stack using lists


def isempty(stk):
if stk==[]:
return True
else:
return False

def push(stack,item):
stack.append(item)
top=len(stack)-1

def pop(stack):
if isempty(stack):
print("underflow")
else:
item=stack.pop()
if len(stack)==0:
top=None
else:
top=len(stack)-1
return item

def display(stk):
if isempty(stk):
print("stack empty")
else:
top=len(stk)-1
print(stk[top])
for a in range(top-1,-1,-1):
print(stk[a])
def peek(stk):
if isempty(stk):
return "underflow"
else:
top=len(stk)-1
return stk[top]

#main
stack=[]
top=None
while True:
print("Stack operations")
print("1.Push")
print("2.Pop")
print("3.Display")
print("4.Peek")
ch=int(input("Enter your choice:(1-2-3)"))
if ch==1:
item=int(input("Enter item:"))
push(stack,item)
elif ch==2:
item=pop(stack)
print("popped item is:",item)
elif ch==3:
display(stack)
elif ch==4:
item=peek(stack)
print("top most item is:",item)
else:
print("invalid choice")
break
Program 2:

Aim: To write a program to PUSH(Books) and POP(Books) methods in Python


to add books and remove books considering them to act as Push and
Pop operations of Stack.

Program Code:

def isempty(stk):
if stk==[]:
return True
else:
return False
def push(books):
item=input("Enter book name:")
books.append(item)
def pop(books):
if books==[]:
print("underflow")
else:
print("deleted item is:",books.pop())
def display(books):
if isempty(books):
print("stack empty")
else:
top=len(books)-1
print(books[top])
for i in range(top-1,-1,-1):
print(books[i])

books=[]
while True:
print("Stack operations")
print("1.Push")
print("2.Pop")
print("3.Display")
ch=int(input("Enter choice:(1/2/3)"))
if ch==1:
push(books)
elif ch==2:
pop(books)
elif ch==3:
display(books)
else:
print("thank u")
break
Program 3:

Aim: To 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 atleast one element, otherwise
display appropriate message.

Program Code:

def PUSH(Arr):
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("The number divisible by 5 is:",s)
n=int(input("Enter number of elements:"))
Arr=[]
for i in range(0,n):
ele=int(input("Enter list of numbers:\n"))
Arr.append(ele)
PUSH(Arr)

You might also like