Data Structure in Python
STACK
Data Structure
2. Tuple
3. Dictionary
4. Set
STACK :
Operations on Stack:
There are two main operations on Stack: PUSH & POP
Addition of element on the Top of the Stack is called PUSH and Deletion of element from the Top of the Stack is called POP.
In the form of List the above stack can be shown as.
The implementation of stack using list is a simple process as there are inbuilt function which we used during working with stack.
How to add elements to a stack?
How to delete / remove elements from the stack
How to traverse or displaying elements of stack?
How to check for empty stack?
st.append(5)
Here element ‘5’ is added into a stack named ‘st’
NOTE : We can add element only at the end of the list as we are implementing list as stack.
3. Deleting elements from the stack :
st.pop( )
NOTE : We can remove or delete element only from the end of the list as we are implementing list as stack.
4. Displaying all elements of the stack :
if (st == [ ]) :
Practical Implementation of Stack using List
st=[ ]
def push(st):
sn=input("Enter name of student")
st.append(sn)
def pop(st):
if(st==[]):
print("Stack is empty")
else:
print("Deleted student name :",st.pop())
Q2. Write a function push(number) and pop(number) to add a number (Accepted from the user) and remove a number from a list of numbers, considering them act as PUSH and POP operations of Data Structure in Python.
st=[ ]
def push(st):
sn=input("Enter any Number")
st.append(sn)
def pop(st):
if(st==[]):
print("Stack is empty")
else:
print("Deleted Number is :",st.pop())
Q3. Write PushOn(Book) and Pop(Book) methods/functions in Python to add a new Book and delete a Book from a list of Book titles, considering them to act as push and pop operations of the Stack data structure.
def PushOn(Book):
a=input(“enter book title :”)
Book.append(a)
def Pop(Book):
if (Book = =[ ]):
print(“Stack empty”)
else:
print(“Deleted element :”)
Book.pop()
Q4. Write a menu based program to add, delete and display the record of hostel using list as stack data structure in python. Record of hostel contains the fields : Hostel number, Total Students and Total Rooms
host=[ ]
ch='y'
def push(host):
hn=int(input("Enter hostel number"))
ts=int(input("Enter Total students"))
tr=int(input("Enter total rooms"))
temp=[hn,ts,tr]
host.append(temp)
def pop(host):
if(host==[]):
print("No Record")
else:
print("Deleted Record is :",host.pop())
def display(host):
l=len(host)
print("Hostel Number\tTotal Students\tTotal Rooms")
for i in range(l-1,-1,-1):
print(host[i][0],"\t\t",host[i][1],"\t\t",host[i][2])
while(ch=='y' or ch=='Y'):
print("1. Add Record\n")
print("2. Delete Record\n")
print("3. Display Record\n")
print("4. Exit")
op=int(input("Enter the Choice"))
if(op==1):
push(host)
elif(op==2):
pop(host)
elif(op==3):
display(host)
elif(op==4):
break
ch=input("Do you want to enter more(Y/N)")
No comments:
Post a Comment