Data Structure
What is DATA STRUCTURE?
Simple Words: Organising data in memory and defining the operations for the stored data
A data structure is a specialized format for organizing, processing, retrieving and storing data.
There are four built-in data structures in Python - list, tuple, dictionary and set.
List
STACKS
TWO MAJOR OPERATIONS
STACKS
Every day examples of stacks:
• Stack of plates/books in a cupboard
• Stack of chairs
• Wearing and removing bangles
Practical applications of stack:
• Undo operation (generally in editors, drawing app)
• Back (in history) button in browsers
• Compilers: Maintaining function calls
• Compilers: Evaluating mathematical expressions
• Reversing strings
• Compilers: Parenthesis checking
• Evaluation of Postfix expression
• Conversion from Infix to Postfix expression
STACKS
Push Operations Pop Operations (Undo)
5
4
3 Underline
2 Bold
1 Change Colour
0 Type Text
We will use a list to implement stack
Push() - append() method of list We keep track of topmost element of Stack
Pop() - pop() method of list Insertions take place at top end
Removals take place at top end
Push(67) Push(88) Pop() Push(100)
a.append(67) a.append(88) a.pop() a.append(100
a=[] 88
)
5 5 5 5 5
4 4 4 4 4
3 3 3 3 3
2 2 2 2 2
1 1 1 88 1 1 100
0 0 67 0 67 0 67 0 67
def push_stack(element):
a.append(element) CODE FOR IMPLEMENTING A STACK USING A LIST
def pop_stack():
if len(a)<=0:
print("Underflow: stack is empty")
else:
x=a.pop()
print("Element popped out of the stack ",x)
a=[]
ch="y"
def display_stack(): while(ch=="y"):
for i in range(len(a)-1,-1,-1): print()
print(a[i]) choice=int(input("Enter 1 to push element, 2 to pop element, 3 to display stack elements"))
if choice==1:
elem=input("Enter element to be pushed in: ")
push_stack(elem)
elif choice==2:
pop_stack()
elif choice==3:
display_stack()
else:
print("Invalid option")
ch=input("Enter y to continue: ")
SOLUTION -----→
if len(BooksStack)==0:
if len(BooksStack)==0: