SAVITRIBAI PHULE PUNE UNIVERSITY
MASTER OF COMPUTER APPLICATION
DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105
STUDENT NAME:
CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….
DATE OF SUBMISSION :-………………………………………………………………………….
TITLE :- 1 Write a program to perform using NumPy to perform Various functions in Array.
Program :
import numpy as np
# Creating an array
arr = [Link]([10, 20, 30, 40, 50])
# Various operations
print("Original Array:", arr)
print("Sum of array:", [Link](arr))
print("Mean of array:", [Link](arr))
print("Max value:", [Link](arr))
print("Min value:", [Link](arr))
print("Sorted Array:", [Link](arr))
print("Square of each element:", [Link](arr))
Output :
1
SAVITRIBAI PHULE PUNE UNIVERSITY
MASTER OF COMPUTER APPLICATION
DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105
STUDENT NAME:
CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….
DATE OF SUBMISSION :-………………………………………………………………………….
TITLE :- 2 Write a program to implement a Sparse Matrix.
Program :
import numpy as np
def sparse_matrix(matrix):
sparse = []
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] != 0:
[Link]((i, j, matrix[i][j]))
return sparse
# Input Matrix
matrix = [
[5, 0, 0],
[0, 8, 0],
[0, 0, 3]
print("Original Matrix:")
for row in matrix:
print(row)
print("Sparse Matrix Representation:")
2
print(sparse_matrix(matrix))
Output :
3
SAVITRIBAI PHULE PUNE UNIVERSITY
MASTER OF COMPUTER APPLICATION
DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105
STUDENT NAME:
CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….
DATE OF SUBMISSION :-………………………………………………………………………….
TITLE :- 3 Write a program to perform String Manipulations using Array.
Program :
from array import array
def string_manipulations(s):
arr = array('u', s) # Unicode array
print("Original String Array:", "".join(arr))
# Reversing the string
[Link]()
print("Reversed String:", "".join(arr))
# Adding a character
[Link]('!')
print("After Adding a Character:", "".join(arr))
# Removing a character
[Link]()
print("After Removing Last Character:", "".join(arr))
string_manipulations("hello")
4
Output :
5
SAVITRIBAI PHULE PUNE UNIVERSITY
MASTER OF COMPUTER APPLICATION
DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105
STUDENT NAME:
CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….
DATE OF SUBMISSION :-………………………………………………………………………….
TITLE :- 10 Write a program to perform the following operations:
a) Insert an element into a binary search tree.
b) Delete an element from a binary search tree.
c) Search for a key element in a binary search tree
Program :
class Node:
def init (self, key):
[Link] = None
[Link] = None
[Link] = key
# Insert function
def insert(root, key):
if root is None:
return Node(key)
elif key < [Link]:
[Link] = insert([Link], key)
else:
[Link] = insert([Link], key)
return root
# Delete function
def delete(root, key):
30
if root is None:
return root
if key < [Link]:
[Link] = delete([Link], key)
elif key > [Link]:
[Link] = delete([Link], key)
else:
# Node with one or no child
if [Link] is None:
return [Link]
elif [Link] is None:
return [Link]
# Node with two children: get the inorder successor
temp = find_min([Link])
[Link] = [Link]
[Link] = delete([Link], [Link])
return root
# Find the minimum value (used in deletion)
def find_min(node):
current = node
while [Link] is not None:
current = [Link]
return current
# Search function
def search(root, key):
if root is None or [Link] == key:
return root
31
if key < [Link]:
return search([Link], key)
return search([Link], key)
# Inorder Traversal (to display BST elements)
def inorder(root):
if root:
inorder([Link])
print([Link], end=" ")
inorder([Link])
# Menu-Driven Program
root = None
while True:
print("\n1. Insert 2. Delete 3. Search 4. Display (Inorder) 5. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
key = int(input("Enter key to insert: "))
root = insert(root, key)
elif choice == 2:
key = int(input("Enter key to delete: "))
root = delete(root, key)
elif choice == 3:
key = int(input("Enter key to search: "))
result = search(root, key)
if result:
print(f"Key {key} found in the BST")
else:
print(f"Key {key} not found in the BST")
32
elif choice == 4:
print("BST Elements (Inorder Traversal): ", end="")
inorder(root)
print()
elif choice == 5:
break
Output :
33
SAVITRIBAI PHULE PUNE UNIVERSITY
MASTER OF COMPUTER APPLICATION
DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105
STUDENT NAME:
CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….
DATE OF SUBMISSION :-………………………………………………………………………….
TITLE :- 11 Write a program to search an element by using Linear search method
Program :
def linear_search(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i # Return index if found
return -1 # Return -1 if not found
# Input and Testing
arr = list(map(int, input("Enter array elements: ").split()))
x = int(input("Enter element to search: "))
result = linear_search(arr, x)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")
Output :
34
SAVITRIBAI PHULE PUNE UNIVERSITY
MASTER OF COMPUTER APPLICATION
DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105
STUDENT NAME:
CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….
DATE OF SUBMISSION :-………………………………………………………………………….
TITLE :- 12 Write a program to search an element by using Binary search method
Program :
def binary_search(arr, x):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == x:
return mid
elif arr[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1
# Input and Testing
arr = sorted(list(map(int, input("Enter sorted array elements: ").split())))
x = int(input("Enter element to search: "))
result = binary_search(arr, x)
if result != -1:
print(f"Element found at index {result}")
else:
35
print("Element not found")
Output :
36
SAVITRIBAI PHULE PUNE UNIVERSITY
MASTER OF COMPUTER APPLICATION
DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105
STUDENT NAME:
CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….
DATE OF SUBMISSION :-………………………………………………………………………….
TITLE :- 13 Write a program to implement the tree traversal methods.
Program :
class Node:
def init (self, key):
[Link] = None
[Link] = None
[Link] = key
# Traversal Functions
def preorder(root):
if root:
print([Link], end=" ")
preorder([Link])
preorder([Link])
def inorder(root):
if root:
inorder([Link])
print([Link], end=" ")
inorder([Link])
def postorder(root):
if root:
postorder([Link])
37
postorder([Link])
print([Link], end=" ")
# Insert into Binary Tree
def insert(root, key):
if root is None:
return Node(key)
elif key < [Link]:
[Link] = insert([Link], key)
else:
[Link] = insert([Link], key)
return root
# Menu-Driven Program
root = None
while True:
print("\n1. Insert 2. Preorder 3. Inorder 4. Postorder 5. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
key = int(input("Enter key to insert: "))
root = insert(root, key)
elif choice == 2:
print("Preorder Traversal: ", end="")
preorder(root)
print()
elif choice == 3:
print("Inorder Traversal: ", end="")
inorder(root)
print()
38
elif choice == 4:
print("Postorder Traversal: ", end="")
postorder(root)
print()
elif choice == 5:
break
Output :
39
SAVITRIBAI PHULE PUNE UNIVERSITY
MASTER OF COMPUTER APPLICATION
DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105
STUDENT NAME:
CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….
DATE OF SUBMISSION :-………………………………………………………………………….
TITLE :- 14 Write a program to perform the following operations:
Insert an element into a AVL tree.
Delete an element from a AVL tree.
Search for a key element in a AVL tree.
Program :
class Node:
def init (self, key):
[Link] = key
[Link] = None
[Link] = None
[Link] = 1
def get_height(node):
if not node:
return 0
return [Link]
def get_balance(node):
if not node:
return 0
return get_height([Link]) - get_height([Link])
def rotate_right(y):
40
x = [Link]
T2 = [Link]
[Link] = y
[Link] = T2
[Link] = 1 + max(get_height([Link]), get_height([Link]))
[Link] = 1 + max(get_height([Link]), get_height([Link]))
return x
def rotate_left(x):
y = [Link]
T2 = [Link]
[Link] = x
[Link] = T2
[Link] = 1 + max(get_height([Link]), get_height([Link]))
[Link] = 1 + max(get_height([Link]), get_height([Link]))
return y
# Insert operation
def insert(node, key):
if not node:
return Node(key)
if key < [Link]:
[Link] = insert([Link], key)
else:
[Link] = insert([Link], key)
[Link] = 1 + max(get_height([Link]), get_height([Link]))
balance = get_balance(node)
# Left heavy
41
if balance > 1 and key < [Link]:
return rotate_right(node)
# Right heavy
if balance < -1 and key > [Link]:
return rotate_left(node)
# Left-Right heavy
if balance > 1 and key > [Link]:
[Link] = rotate_left([Link])
return rotate_right(node)
# Right-Left heavy
if balance < -1 and key < [Link]:
[Link] = rotate_right([Link])
return rotate_left(node)
return node
# Inorder Traversal
def inorder(node):
if node:
inorder([Link])
print([Link], end=" ")
inorder([Link])
# Search operation
def search(node, key):
if not node or [Link] == key:
return node
if key < [Link]:
return search([Link], key)
42
return search([Link], key)
# Menu-driven Program
root = None
while True:
print("\n1. Insert 2. Search 3. Display Inorder 4. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
key = int(input("Enter key to insert: "))
root = insert(root, key)
elif choice == 2:
key = int(input("Enter key to search: "))
result = search(root, key)
print(f"Key {key} found" if result else f"Key {key} not found")
elif choice == 3:
print("Inorder Traversal of AVL Tree: ", end="")
inorder(root)
print()
elif choice == 4:
break
43
Output :
44
SAVITRIBAI PHULE PUNE UNIVERSITY
MASTER OF COMPUTER APPLICATION
DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105
STUDENT NAME:
CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….
DATE OF SUBMISSION :-………………………………………………………………………….
TITLE :- 15 Write a program to implement the Graph methods.
Adjacency Matrix
Adjacency List
Program :
# Graph using Adjacency Matrix
def adjacency_matrix(vertices, edges):
matrix = [[0] * vertices for _ in range(vertices)]
for edge in edges:
u, v = edge
matrix[u][v] = 1
matrix[v][u] = 1 # For undirected graph
return matrix
# Graph using Adjacency List
def adjacency_list(vertices, edges):
adj_list = {i: [] for i in range(vertices)}
for edge in edges:
u, v = edge
adj_list[u].append(v)
adj_list[v].append(u) # For undirected graph
return adj_list
45
# Input
vertices = int(input("Enter number of vertices: "))
edges_count = int(input("Enter number of edges: "))
edges = []
for _ in range(edges_count):
u, v = map(int, input("Enter edge (u, v): ").split())
[Link]((u, v))
# Output
print("\nAdjacency Matrix:")
matrix = adjacency_matrix(vertices, edges)
for row in matrix:
print(row)
print("\nAdjacency List:")
adj_list = adjacency_list(vertices, edges)
for key, value in adj_list.items():
print(f"{key}: {value}")
Output :
46
SAVITRIBAI PHULE PUNE UNIVERSITY
MASTER OF COMPUTER APPLICATION
DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105
STUDENT NAME:
CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….
DATE OF SUBMISSION :-………………………………………………………………………….
TITLE :- 16 Write a program to implement the Graph traversal methods
BFS
DFS
Program :
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
print("BFS Traversal: ", end="")
while queue:
node = [Link]()
if node not in visited:
print(node, end=" ")
[Link](node)
for neighbor in graph[node]:
if neighbor not in visited:
[Link](neighbor)
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
[Link](start)
47
print(start, end=" ")
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
# Input
vertices = int(input("Enter number of vertices: "))
edges_count = int(input("Enter number of edges: "))
graph = {i: [] for i in range(vertices)}
for _ in range(edges_count):
u, v = map(int, input("Enter edge (u, v): ").split())
graph[u].append(v)
graph[v].append(u)
# Traversal
start = int(input("Enter starting vertex: "))
bfs(graph, start)
print("\nDFS Traversal: ", end="")
dfs(graph, start)
48
Output :
49
SAVITRIBAI PHULE PUNE UNIVERSITY
MASTER OF COMPUTER APPLICATION
DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105
STUDENT NAME:
CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….
DATE OF SUBMISSION :-………………………………………………………………………….
TITLE :- 17 Write a program to sort an elements by using Bubble sort method .
Program :
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
# Input and Testing
arr = list(map(int, input("Enter elements to sort: ").split()))
bubble_sort(arr)
print("Sorted Array:", arr)
Output :
50
SAVITRIBAI PHULE PUNE UNIVERSITY
MASTER OF COMPUTER APPLICATION
DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105
STUDENT NAME:
CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….
DATE OF SUBMISSION :-………………………………………………………………………….
TITLE :- 18 Write a program to sort an elements by using Merge sort method .
Program :
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
arr[k] = left_half[i]
i += 1
else:
arr[k] = right_half[j]
j += 1
k += 1
while i < len(left_half):
51
arr[k] = left_half[i]
i += 1
k += 1
while j < len(right_half):
arr[k] = right_half[j]
j += 1
k += 1
# Input and Testing
arr = list(map(int, input("Enter elements to sort: ").split()))
merge_sort(arr)
print("Sorted Array:", arr)
Output :
52
SAVITRIBAI PHULE PUNE UNIVERSITY
MASTER OF COMPUTER APPLICATION
DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105
STUDENT NAME:
CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….
DATE OF SUBMISSION :-………………………………………………………………………….
TITLE :- 19 Write a program to sort an elements by using Quick sort method.
Program :
def partition(arr, low, high):
pivot = arr[high] # Choose the last element as the pivot
i = low - 1 # Index of smaller element
for j in range(low, high):
if arr[j] < pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i] # Swap
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return i + 1
def quick_sort(arr, low, high):
if low < high:
pi = partition(arr, low, high) # Partitioning index
quick_sort(arr, low, pi - 1) # Sort elements before partition
quick_sort(arr, pi + 1, high) # Sort elements after partition
# Input and Testing
arr = list(map(int, input("Enter elements to sort: ").split()))
quick_sort(arr, 0, len(arr) - 1)
print("Sorted Array:", arr)
53
Output :
54
SAVITRIBAI PHULE PUNE UNIVERSITY
MASTER OF COMPUTER APPLICATION
DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105
STUDENT NAME:
CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….
DATE OF SUBMISSION :-………………………………………………………………………….
TITLE :- 20 Write a program that implements the following methods
Heap sort.
Program :
def heapify(arr, n, i):
largest = i # Initialize the largest as root
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left] > arr[largest]:
largest = left
if right < n and arr[right] > arr[largest]:
largest = right
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, n, largest)
def heap_sort(arr):
n = len(arr)
for i in range(n // 2 - 1, -1, -1): # Build a max heap
heapify(arr, n, i)
55
for i in range(n - 1, 0, -1): # Extract elements
arr[i], arr[0] = arr[0], arr[i]
heapify(arr, i, 0)
# Input and Testing
arr = list(map(int, input("Enter elements to sort: ").split()))
heap_sort(arr)
print("Sorted Array:", arr)
Output :
56
SAVITRIBAI PHULE PUNE UNIVERSITY
MASTER OF COMPUTER APPLICATION
DR.D.Y. PATIL SCHOOL OF MCA
Charoli (bk) pune-412105
STUDENT NAME:
CLASS :-………… DIVISION :-……….. ROLL NO :-…………… REMARK :-…………….
DATE OF SUBMISSION :-………………………………………………………………………….
TITLE :- 21 Write a program that implements the Hash Methods
Program :
class HashTable:
def init (self, size):
[Link] = size
[Link] = [None] * size
def hash_function(self, key):
return key % [Link]
def insert(self, key):
index = self.hash_function(key)
if [Link][index] is None:
[Link][index] = key
else:
print(f"Collision occurred for key {key} at index {index}")
def search(self, key):
index = self.hash_function(key)
if [Link][index] == key:
print(f"Key {key} found at index {index}")
else:
print(f"Key {key} not found")
57
def display(self):
print("Hash Table:")
for i, value in enumerate([Link]):
print(f"Index {i}: {value}")
# Menu-driven program
size = int(input("Enter size of hash table: "))
hash_table = HashTable(size)
while True:
print("\n1. Insert 2. Search 3. Display 4. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
key = int(input("Enter key to insert: "))
hash_table.insert(key)
elif choice == 2:
key = int(input("Enter key to search: "))
hash_table.search(key)
elif choice == 3:
hash_table.display()
elif choice == 4:
break
58
Output :
59