Stack Notes
Stack Notes
It is
an abstract data type. A Stack works on the LIFO process (Last In First Out), i.e., the
element that was inserted last will be removed first. To implement the Stack, it is
required to maintain a pointer to the top of the Stack, which is the last element to be
inserted because we can access the elements only on the top of the Stack.
def push(a,val):
a.append(val)
def pop(a):
item=a.pop()
print("popped item=",item)
def peek(a):
last=len(a)-1
print("peek element=",a[last])
def display(a):
for i in range(len(a)-1,-1,-1):
print(a[i])
a=[]
while True:
choice=int(input("enter choice"))
if choice==1:
val=int(input("Enter number to insert:"))
push(a,val)
print("Element pushed successfully")
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)
else:
break;
Output:
enter choice1
Enter number to insert:20
Element pushed successfully
enter choice1
Enter number to insert:15
Element pushed successfully
enter choice2
popped item= 15
enter choice3
peek element= 20
enter choice4
20
Example 2
Question no 4
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:
3
9
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:-
Q- 5 Write a function to push student info
into stack