DSA - Practical - File (1) Sagar Kumar
DSA - Practical - File (1) Sagar Kumar
DSEU
Shakarpur Campus
2
Practical File
Submitted to:
Submitted by:
Mrs. Barkha Nandwana sagar
kumar
Roll no.-40822028
B.Sc. Data
Analytics ( III SEM)
rd
INDEX
S.No Practicals Date Teacher’
. s Sign
1. Practical1. Write a program to 23/08/23
perform basic array functions in 1-
D array.
2. Practical2. Write a program to 30/08/23
perform basic array functions in 2-
D array.
3. Practical3. Write a program to find 06/09/23
a desired item using Linear Search.
4. Practical4. Write a program to find 06/09/23
a desired item using Binary Search.
5. Practical5. Write a program to sort 13/09/23
an array using Bubble sort.
6. Practical6. Write a program to sort 20/09/23
an array using Merge sort.
7. Practical7. Write a program to sort 20/09/23
an array using Selection sort.
8. Practical8. Write a program to sort 27/09/23
an array using Insertion sort.
9. Practical9. Write a program to sort 27/09/23
an array using Shell sort.
10. Practical10. Write a program to 04/10/23
sort an array using Quick sort.
11. Practical11. Write a program to 05/10/23
find Fibonacci sequence.
12. Practical12. Write a program to 05/10/23
find factorial of a given input.
13. Practical13. Write a program to 11/10/202
insert elements in stack. 3
14. Practical14. Write a program to 11/10/202
delete elements from stack. 3
15. Practical15. Write a program to 18/10/202
convert infix to prefix expression. 3
16. Practical16. Write a program to 18/10/202
convert infix to postfix expression. 3
17. Practical17. Write a program for 25/10/202
queue implementation. 3
18. Practical18. Write a program for 25/10/202
inorder, preorder, postorder 3
traversal.
19. Practical19. Write a program for 08/11/202
Binary Tree in python. 3
20. Practical20. Write a program for 15/11/202
searching in Binary Search Tree 3
21. Practical21. Write a program for 22/11/202
insertion in BST. 3
22. Practical22. Write a program for 29/11/202
deletion in BST. 3
23. Practical23. Write a program 29/11/202
for Balanced Binary Tree/ 3
AVL Tree.
24. Practical24. Write a program for 06/12/202
Binary Heap Tree. 3
25. Practical25. Write a program for 06/12/202
Graph Implementation. 3
Practical 1: Write a program to perform basic array functions in 1-D
array.
Form a 1-D array
Input: import numpy as np
import array
arr=array.array('i',[2,3,4,5,7,9,1,2,3])
arr
Output:
(ii) starting
Input: arr[0:]
Output:
Update an array
Input: arr[4]=10
arr
Output:
Delete an element
Input: del arr[4]
arr
arr.pop(5)
arr
Output:
Reverse an array
Input: arr.reverse()
arr
Output:
Practical 2: Write a program to perform basic array functions in 2-D
array.
Form a 2-D array
Input: import numpy as np
arr1=np.array([[2,3,5,9],[10,23,37,12]])
arr1
arr2=np.array([[234,455,323,787],[204,653,709,900]])
arr2
Output:
Addition
Input: np.add(arr1,arr2)
Output:
Subtraction
Input: np.subtract(arr2,arr1)
Output:
Multiplication
Input: arr1*arr2
Output:
Division
Input: arr1/arr2
Output:
Practical3. Write a program to find a desired item using Linear Search.
Input: a = [4, 6, 9, 12, 15, 20, 85, 45]
x = int(input("Enter the element you want to find: "))
for i in range(len(a)):
if a[i] == x:
print(f"Element {x} found at index {i}")
break
else:
print(f"Element {x} not found in the list")
Output:
Practical4. Write a program to find a desired item using Binary
Search.
Input: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
item=int(input("enter the item number"))
LB=0
UB=len(arr) - 1
while LB <= UB:
mid = (LB + UB) // 2
if arr[mid] == item:
print("Item", {item}, "found at index",{mid})
break
elif arr[mid] < item:
LB = mid + 1
else:
UB = mid - 1
else:
print("Item",{item},"not found in the array")
Output:
Practical5. Write a program to sort an array using Bubble sort.
Input: l=[12,1,2343,89,345,89,9,34,15,200]
n = len(l)
for i in range(n):
for j in range(0, n - i - 1):
if l[j] > l[j + 1]:
l[j], l[j + 1] = l[j + 1], l[j]
print("Sorted list:", l)
Output:
Practical 6: Write a program to sort an array using Merge sort.
Input: arr = [12, 11, 13, 5, 6, 7]
var= [(0, len(arr))]
temp = [0] * len(arr)
while var:
left, right = var.pop()
if left + 1 < right:
mid = (left + right) // 2
var.append((left, mid))
var.append((mid, right))
i = left
j = mid
for k in range(left, right):
if i < mid and (j >= right or arr[i] <= arr[j]):
temp[k] = arr[i]
i += 1
else:
temp[k] = arr[j]
j += 1
for k in range(left, right):
arr[k] = temp[k]
print("Sorted array:", arr)
Output:
Practical 7: Write a program to sort an array using Selection sort.
Input: arr =[23,43,10,13,90,22,50,34,64,70]
for i in range(len(arr)):
min_index = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
print("Sorted array:", arr)
Output:
Practical 8: Write a program to sort an array using Insertion sort.
Input: arr=[23,43,10,13,90,22,50,34,64,70]
for i in range (1,len(arr)):
temp=arr[i]
j=i-1
while j>=0 and temp<arr[j]:
arr[j+1]=arr[j]
j-=1
arr[j+1]=temp
print('sorted array:',arr)
Output:
Practical 9: Write a program to sort an array using Shell sort.
Input: arr=[23,43,10,13,90,22,50,34,64,70]
n=len(arr)
sub_lst=n/2
sub_lst>0;
for i in range (1,len(arr)):
temp=arr[i]
j=i-1
while j>=0 and temp<arr[j]:
arr[j+1]=arr[j]
j-=1
arr[j+1]=temp
lst=sub_lst/2
print('sorted array:',arr)
Output:
Practical 10: Write a program to sort an array using Quick sort.
Input: def quick_sort(arr):
arr=[23,43,10,13,90,22,50,34,64,70]
if len(arr) <= 1:
sorted_arr = arr
else:
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
sorted_arr = quick_sort(arr) + middle + quick_sort(right)
print('sorted_arr:',arr)
Output:
Practical 11: Write a program to find Fibonacci sequence.
Input: n=int(input("enter the limit of the series"))
x=0
y=1
print(x,y, end=' ')
while x<=n:
z=x+y
x=y
y=z
print(z,end=' ')
Output:
Practical 12: Write a program to find factorial of a given input .
Input: def fact(n):
if (n==0 or n==1):
return 1
else:
return(n*fact(n-1))
n=int(input("enter the number"))
print("the factorial of",n,"is",fact(n))
Output:
Practical13. Write a program to insert elements in stack.
Input: stack = []
def push(item):
stack.append(item)
push(1)
push(2)
push(3)
print(stack)
Output:
Practical14. Write a program to delete elements from stack.
Input: def pop(stack1):
if not stack1.is_empty():
return stack1.items.pop()
else:
return "Stack1 is empty"
deleted_items=stack1.pop()
print("Deleted item:", deleted_items)
Output:
Practical15. Write a program to convert infix to prefix expression.
Input: def isOperator(c):
return (not c.isalpha()) and (not c.isdigit())
def getPriority(c):
if c == '-' or c == '+':
return 1
elif c == '*' or c == '/':
return 2
elif c == '^':
return 3
return 0
def infixToPostfix(infix):
infix = '(' + infix + ')'
l = len(infix)
char_stack = []
output = ""
for i in range(l):
if infix[i].isalpha() or infix[i].isdigit():
output += infix[i]
elif infix[i] == '(':
char_stack.append(infix[i])
elif infix[i] == ')':
while char_stack[-1] != '(':
output += char_stack.pop()
char_stack.pop()
else:
if isOperator(char_stack[-1]):
if infix[i] == '^':
while getPriority(infix[i]) <= getPriority(char_stack[-1]):
output += char_stack.pop()
else:
while getPriority(infix[i]) < getPriority(char_stack[-1]):
output += char_stack.pop()
char_stack.append(infix[i])
while len(char_stack) != 0:
output += char_stack.pop()
return output
def infixToPrefix(infix):
l = len(infix)
infix = infix[::-1]
for i in range(l):
if infix[i] == '(':
infix[i] = ')'
elif infix[i] == ')':
infix[i] = '('
prefix = infixToPostfix(infix)
prefix = prefix[::-1]
return prefix
if __name__ == '__main__':
s = "x+y*z/w+u"
# Function call
print(infixToPrefix(s))
Output:
Practical16. Write a program to convert infix to postfix expression.
Input: # Class to convert the expression
class Conversion:
# Constructor to initialize the class variables
def __init__(self, capacity):
self.top = -1
self.capacity = capacity
# This array is used a stack
self.array = []
# Precedence setting
self.output = []
self.precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
# Check if the stack is empty
def isEmpty(self):
return True if self.top == -1 else False
# Return the value of the top of the stack
def peek(self):
return self.array[-1]
# Pop the element from the stack
def pop(self):
if not self.isEmpty():
self.top -= 1
return self.array.pop()
else:
return "$"
# Push the element to the stack
def push(self, op):
self.top += 1
self.array.append(op)
# A utility function to check is the given character is operand
def isOperand(self, ch):
return ch.isalpha()
# Check if the precedence of operator is strictly less than top of stack or not
def notGreater(self, i):
try:
a = self.precedence[i]
b = self.precedence[self.peek()]
return True if a <= b else False
except KeyError:
return False
# The main function that converts given infix expression to postfix expression
def infixToPostfix(self, exp):
# Iterate over the expression for conversion
for i in exp:
# If the character is an operand,add it to output
if self.isOperand(i):
self.output.append(i)
# If the character is an '(', push it to stack
elif i == '(':
self.push(i)
# If the scanned character is an ')', pop and output from the stack until and '(' is found
elif i == ')':
while((not self.isEmpty()) and
self.peek() != '('):
a = self.pop()
self.output.append(a)
if (not self.isEmpty() and self.peek() != '('):
return -1
else:
self.pop()
# An operator is encountered
else:
while(not self.isEmpty() and self.notGreater(i)):
self.output.append(self.pop())
self.push(i)
# Pop all the operator from the stack
while not self.isEmpty():
self.output.append(self.pop())
for ch in self.output:
print(ch, end="")
# Driver code
if __name__ == '__main__':
exp = "a+b*(c^d-e)^(f+g*h)-i"
obj = Conversion(len(exp))
# Function call
obj.infixToPostfix(exp)
Output:
Practical17. Write a program for queue implementation.
Input: from collections import deque
q = deque()
q.append('a')
q.append('b')
q.append('c')
print("Initial queue")
print(q)
print("\nElements dequeued from the queue")
print(q.popleft())
print(q.popleft())
print(q.popleft())
print("\nQueue after removing elements")
print(q)
Output:
Practical18. Write a program for inorder, preorder, postorder
traversal.
Input: class Node:
def __init__(self, item):
self.left = None
self.right = None
self.val = item
def inorder(root):
if root:
inorder(root.left)
print(str(root.val) + "->", end='')
inorder(root.right)
def postorder(root):
if root:
postorder(root.left)
postorder(root.right)
print(str(root.val) + "->", end='')
def preorder(root):
if root:
print(str(root.val) + "->", end='')
preorder(root.left)
preorder(root.right)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print("Inorder traversal ")
inorder(root)
print("\nPreorder traversal ")
preorder(root)
print("\nPostorder traversal ")
postorder(root)
Output:
Practical19. Write a program for Binary Tree in python
Input: from binarytree import Node
root = Node(3)
root.left = Node(6)
root.right = Node(8)
Output:
Practical20. Write a program for searching in Binary Search Tree
Input:
# Creating a binary search tree
from binarytree import Node
root = Node(9)
root.left = Node(1)
root.right = Node(10)
root.left.left = Node(0)
root.left.right = Node(3)
root.left.right.right = Node(4)
print("Binary Tree:", root)
# Defining a function that will search the given value of x in the tree
def search(root, x):
Output:
Practical21. Write a program for insertion in BST.
Input: class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
if root is None:
return Node(x)
else:
if root.val == x:
return root
root.right = insert(root.right, x)
else:
root.left = insert(root.left, x)
return root
root = Node(9)
root.left = Node(1)
root.right = Node(10)
root.left.left = Node(0)
root.left.right = Node(3)
root.left.right.right = Node(4)
x=5
v = insert(root, x)
Output:
Practical22. Write a program for deletion in BST.
Input:
def deleteNode(root,x):
if root is None:
return root
if x < root.val:
root.left = deleteNode(root.left, x)
root.right = deleteNode(root.right, x)
else:
if root.left is None:
temp = root.right
root = None
return temp
temp = root.left
root = None
return temp
temp = minValueNode(root.right)
root.val = temp.val
return root
x=5
root = deleteNode(root, x)
Output:
Practical23. Write a program for Balanced Binary Tree/
AVL Tree.
Input: class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 1
class AVLTree:
def getHeight(self, node):
if not node:
return 0
return node.height
def getBalance(self, node):
if not node:
return 0
return self.getHeight(node.left) - self.getHeight(node.right)
def rightRotate(self, y):
x = y.left
T2 = x.right
x.right = y
y.left = T2
y.height = 1 + max(self.getHeight(y.left), self.getHeight(y.right))
x.height = 1 + max(self.getHeight(x.left), self.getHeight(x.right))
return x
def leftRotate(self, x):
y = x.right
T2 = y.left
y.left = x
x.right = T2
x.height = 1 + max(self.getHeight(x.left), self.getHeight(x.right))
y.height = 1 + max(self.getHeight(y.left), self.getHeight(y.right))
return y
def insert(self, root, key):
if not root:
return Node(key)
if key < root.key:
root.left = self.insert(root.left, key)
else:
root.right = self.insert(root.right, key)
root.height = 1 + max(self.getHeight(root.left), self.getHeight(root.right))
balance = self.getBalance(root)
# Left Left Case
if balance > 1 and key < root.left.key:
return self.rightRotate(root)
# Right Right Case
if balance < -1 and key > root.right.key:
return self.leftRotate(root)
# Left Right Case
if balance > 1 and key > root.left.key:
root.left = self.leftRotate(root.left)
return self.rightRotate(root)
# Right Left Case
if balance < -1 and key < root.right.key:
root.right = self.rightRotate(root.right)
return self.leftRotate(root)
return root
def delete(self, root, key):
# Deletion logic not included for brevity
pass
def inorderTraversal(self, root):
if root:
self.inorderTraversal(root.left)
print(root.key, end=" ")
self.inorderTraversal(root.right)
# Usage example:
def print_tree(root, level=0, prefix="Root: "):
if root is not None:
print(" " * (level * 4) + prefix + str(root.key))
if root.left is not None or root.right is not None:
print_tree(root.left, level + 1, "L--- ")
print_tree(root.right, level + 1, "R--- ")
avl = AVLTree()
root = None
keys = [9, 5, 10, 0, 6, 11, -1, 1, 2]
for key in keys:
if root is None: # Initialize the root node if it's None
root = Node(key)
else:
root = avl.insert(root, key)
print("AVL Tree:")
print_tree(root)
Output:
Practical24. Write a program for Binary Heap Tree.
Input: class BinaryHeapTree:
def __init__(self):
self.heap = []
def insert(self, value):
self.heap.append(value)
self._heapify_up(len(self.heap) - 1)
def delete_min(self):
if len(self.heap) == 0:
return None
if len(self.heap) == 1:
return self.heap.pop()
min_value = self.heap[0]
self.heap[0] = self.heap.pop()
self._heapify_down(0)
return min_value
def _heapify_up(self, index):
parent_index = (index - 1) // 2
while index > 0 and self.heap[index] < self.heap[parent_index]:
self.heap[index], self.heap[parent_index] =
self.heap[parent_index], self.heap[index]
index = parent_index
parent_index = (index - 1) // 2
# Example usage:
graph = Graph()
# Add vertices
graph.add_vertex('A')
graph.add_vertex('B')
graph.add_vertex('C')
graph.add_vertex('D')
# Add edges
graph.add_edge('A', 'B')
graph.add_edge('B', 'C')
graph.add_edge('C', 'D')
graph.add_edge('D', 'A')
Output: