Stack Practice Programs
Stack Practice Programs
def push(a,data):
a.append(data)
print("Element Pushed Successfully...")
def pop(a):
x=a.pop()
print("Popped Element=",x)
def peek(a):
print("Peek Element=",a[-1])
def display(a):
for i in range(len(a)-1,-1,-1):
print(a[i])
#__main__
a=[]
while True:
choice=int(input("1->Push\n2->Pop\n3->Peek\n4->Display All\n5>Exit\nEnter
Your Choice:"))
if choice==1:
data=int(input("Enter Value to Push:"))
push(a,data)
elif choice==2:
if len(a)==0:
print("Stack Underflow...")
else:
pop(a)
elif choice==3:
if len(a)==0:
print("Stack Underflow...")
else:
peek(a)
elif choice==4:
if len(a)==0:
print("Stack Underflow...")
else:
display(a)
elif choice==5:
break
else:
print("Bewakoofi wali choice...")
2. 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)
* 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}
The output from the program should be: TOM ANU BOB OM
Ans)
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
4. 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.
Ans)
def PUSH(Arr,value):
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(s)
5. 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. Ans)
def popStack(st) :
# If stack is empty
if len(st)==0:
print("Underflow")
else:
L = len(st)
val=st[L-1]
print(val)
st.pop(L-1)