Stack Notes
Stack Notes
stack=[]
top=None
d=eval(input("Enter dictionary:"))
def Push(d):
global stack,top
for key in d:
if d[key]>49:
stack.append(key)
top=len(stack)-1
def Pop():
global top,stack
while True: #while top!=None:
if stack==[]:
print("Underflow")
top=None
break
else:
print(stack.pop())
top=len(stack)-1
Push(d)
Pop()
def display():
global top,stack
if stack==[]:
top=None
print(“Stack is empty”)
else:
top=len(stack)-1
for i in range(top,-1,-1):
print(stack[i])
2)FROM LIST TO STACK
stack=[]
set1=eval(input('Enter list of numbers:'))
top=None
def PUSH(stack,set1):
global top,stack
for i in range(len(set1)):
if set1[i]%10==8:
stack.append(set1[i])
top=len(stack)-1
def Pop():
global top,stack
while True:
if stack!=[]:
print(stack.pop())
top=len(stack)-1
else:
print('Underflow')
break
PUSH(stack,set1)
Pop()
R=[]
t=None
STR=eval(input("Enter string:"))
def push(STR):
global t,R
for i in STR:
if i.isupper():
R.append(i)
t=len(R)-1
def Pop():
global t,R
while True:
if R==[]:
t=None
print("Stack is empty")
break
else:
R.pop()
t=len(R)-1
Push(d)
Pop()
def display():
global Top,Book
if Book==[]:
print(“Stack is empty”)
else:
Top=len(Book)-1
for i in range(Top,-1,-1):
print(Book[i])
def Peek():
global Top,Book
if Book==[]:
print(“Stack is empty”)
else:
Top=len(Book)-1
print(Book[Top])
while True:
print('1 - Push')
print('2 - Pop')
print('3 - Display')
print('4 - Peek)
print('5 - Exit')
ch=int(input('Enter your choice '))
if ch==1:
push()
elif ch==2:
pop()
elif ch==3:
display()
elif ch==4:
Peek()
elif ch==5:
break
else:
print('Invalid choice')
THEORY QUESTIONS
What is a stack?
A stack is a linear datastructure that follows the
LIFO method in which insertion and deletion takes
place at one end(from top)
List the applications of stack
Applications of Stack
1.Reversal of a string,list or word.
2.Backtracking of web page in a website
3.Undo operation
4.Expression evaluation
5.Recursive function call
Peek – Inspecting the topmost element
Underflow – Trying to delete an element from an
empty stack
Overflow – Trying to insert elements to a stack
which is full.This situation does not arise in Python
as Lists are dynamic in size