1. “DATA SCIENCE AND ALGORITHM”
NAME: FAISAL MUJAHID
ROLL NO: SU91-BSBIM-F22-032
SUBMITTED TO: MA`AM ZAHIRA ILYAS
2. 2
“INTRODUCTION”
TOPIC: Stack
Certainly! A stack is a fundamental data structure that follows the Last-In-First-
Out (LIFO) principle. It means that the most recently added element is the first one
to be removed. Here's a Python implementation of a stack along with a brief
description of each method:
3. CODING OF MERGE SORT
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
"""Check if the stack is empty.""“
return len(self.items) == 0
def push(self, item):
"""Add an item to the top of the stack."""
3
1
4. self.items.append(item)
def pop(self):
""" Remove and return the item at the top of the stack. Raises an IndexError if
the stack is empty. ""“
if not self.is_empty():
return self.items.pop()
else:
raise IndexError("Stack is empty")
def peek(self):
""" Return the item at the top of the stack without removing it. Raises an IndexError if the
stack is empty. """
4
2
5. if not self.is_empty():
return self.items[-1]
else:
raise IndexError("Stack is empty")
def size(self):
"""Return the number of elements in the stack.""“
return len(self.items)
# Example usage:
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3) 5
3
6. print("Stack:", stack.items) # Output: Stack: [1, 2, 3]
print("Size of stack:", stack.size()) # Output: Size of stack: 3
print("Top of stack:", stack.peek()) # Output: Top of stack: 3
print("Popped item:", stack.pop()) # Output: Popped item: 3
print("Stack after pop:", stack.items) # Output: Stack after pop: [1, 2]
6
4
7. Description:
__init__(self):
The constructor initializes an empty list to store the stack elements.
is_empty(self):
Checks if the stack is empty.
push(self, item):
Adds an item to the top of the stack by appending it to the list.
pop(self):
Removes and returns the top item from the stack, raising an exception if the stack
is empty.
7
6
8. peek(self):
Returns the top item without removing it, raising an exception if the stack is
empty.
size(self):
Returns the number of elements in the stack.
8
7
9. Conclusion:
In conclusion, the Python code provided implements a stack, a fundamental
data structure that follows the Last-In-First-Out (LIFO) principle. The stack is
represented as a list, and various methods are defined to manipulate it. The
push method adds elements to the top of the stack, the pop method
removes and returns the top element, the peek method allows you to view
the top element without removing it, and the size method returns the
number of elements in the stack.
9
8
10. The code demonstrates the basic operations of a stack and how it can be
used to manage a collection of items in a manner where the most recently
added item is the first to be processed or removed. Understanding stacks is
crucial in computer science and programming for tasks like parsing
expressions, backtracking algorithms, and managing function calls in
recursion, among many others.
10
9