0% found this document useful (0 votes)
26 views19 pages

HPC Practical 2025 (3)

The document contains a series of practical programming exercises aimed at implementing various algorithms and techniques using Python. These include Prim's algorithm, linear search, divide and conquer (merge sort), DFS, BFS, Dijkstra's shortest path, convolutional neural networks for number prediction, and regularization for binary classification. Each section provides the aim, code implementation, and output for the respective algorithm or technique.

Uploaded by

Sahil Sayyad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views19 pages

HPC Practical 2025 (3)

The document contains a series of practical programming exercises aimed at implementing various algorithms and techniques using Python. These include Prim's algorithm, linear search, divide and conquer (merge sort), DFS, BFS, Dijkstra's shortest path, convolutional neural networks for number prediction, and regularization for binary classification. Each section provides the aim, code implementation, and output for the respective algorithm or technique.

Uploaded by

Sahil Sayyad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

INDEX

Sr Aim Date Signature


No.
1 Write a program to implement prim's
algorithm using Python language.

2 Write a program to implement linear search


using Python language

3 Write a program to implement Divide and


Concur algorithm using Python language.

4 Write a program to implement DFS algorithm


using Python language.

5 Write a program to implement BFS algorithm


using Python language.

6 Write a program to implement Dijkstra’s


shortest path algorithm using Python
language.
7 Implementation of convolutional neural
network to predict numbers

8 Implementing regularization to avoid


overfitting in binary classification.
Practical No. 01
Aim :- Write a program to implement prim's algorithm using Python language.

CODE:

import sys

def prims_algorithm(graph):

num_vertices = len(graph)

key = [sys.maxsize] * num_vertices # Initialize all keys as infinite

parent = [-1] * num_vertices # To store the MST

key[0] = 0 # Start from the first vertex

mst_set = [False] * num_vertices # Track vertices included in MST

for _ in range(num_vertices):

# Find the vertex with the minimum key value not yet included in MST

u = min((key[v], v) for v in range(num_vertices) if not mst_set[v])[1]

mst_set[u] = True

# Update key values of adjacent vertices

for v in range(num_vertices):

if graph[u][v] and not mst_set[v] and graph[u][v] < key[v]:

key[v] = graph[u][v]

parent[v] = u

# Print the MST

print("Edge \tWeight")
for i in range(1, num_vertices):

print(f"{parent[i]} - {i} \t{graph[i][parent[i]]}")

# Example graph represented as an adjacency matrix

graph = [

[0, 2, 0, 6, 0],

[2, 0, 3, 8, 5],

[0, 3, 0, 0, 7],

[6, 8, 0, 0, 9],

[0, 5, 7, 9, 0]

prims_algorithm(graph)

Output
Practical No. 02
Aim :- Write a program to implement linear search using Python language.

CODE:

def linear_search(a, n, val):


# Going through array sequentially
for i in range(n):
if a[i] == val:
return i + 1 # Returning position (1-based index)
return -1 # Element not found

# Main function
if __name__ == "__main__":
a = [70, 40, 30, 11, 57, 41, 25, 14, 52] # Given array
val = 41 # Value to be searched
n = len(a) # Size of the array

res = linear_search(a, n, val) # Store result

# Display the array


print("The elements of the array are -", ' '.join(map(str, a)))

# Display the element to be searched


print("Element to be searched is -", val)

# Display the search result


if res == -1:
print("Element is not present in the array")
else:
print(f"Element is present at {res} position of the array")

Output
Practical No. 03
Aim :- Write a program to implement Divide and Concur algorithm using Python

CODE:

def merge_sort(arr):
# Base case: if the array has one or no elements, it's
already sorted
if len(arr) <= 1:
return arr

# Divide: split the array into two halves


mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]

# Conquer: recursively sort both halves


left_half = merge_sort(left_half)
right_half = merge_sort(right_half)

# Combine: merge the sorted halves


return merge(left_half, right_half)

def merge(left, right):


result = []
i=j=0

# Merge the two sorted lists


while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1

# Add remaining elements (if any)


result.extend(left[i:])
result.extend(right[j:])

return result

# Example usage
arr = [38, 27, 43, 3, 9, 82, 10]
print("Original Array:", arr)
sorted_arr = merge_sort(arr)
print("Sorted Array:", sorted_arr)

Output :
Practical No. 04
Aim :- Write a program to implement DFS algorithm using Python.

CODE:

# Python program to print DFS traversal for


complete graph from collections import defaultdict:

Graph represented as an adjacency list


graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}

def dfs_recursive(graph, node, visited=None):


if visited is None:
visited = set()

# Visit the node if it's not visited yet


if node not in visited:
print(node, end=' ')
visited.add(node)

# Recursively visit all neighbors


for neighbor in graph[node]:
dfs_recursive(graph, neighbor, visited)

# Starting DFS from node 'A'


print("DFS Traversal (Recursive):")
dfs_recursive(graph, 'A')
def dfs_iterative(graph, start):
visited = set()
stack = [start]

while stack:
node = stack.pop()
if node not in visited:
print(node, end=' ')
visited.add(node)
# Add neighbors to the stack (reversed to maintain order)
stack.extend(reversed(graph[node]))

# Starting DFS from node 'A'


print("\nDFS Traversal (Iterative):")
dfs_iterative(graph, 'A')

Output:
Practical No. 05
Aim :- Write a program to implement BFS algorithm using Python language.

CODE:

from collections import deque

# Graph represented as an adjacency list


graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}

def bfs(graph, start):


visited = set() # To keep track of visited nodes
queue = deque([start]) # Queue for BFS

while queue:
node = queue.popleft() # Dequeue the front node

if node not in visited:


print(node, end=' ') # Visit the node
visited.add(node)

# Enqueue all unvisited neighbors


for neighbor in graph[node]:
if neighbor not in visited:
queue.append(neighbor)

# Starting BFS from node 'A'


print("BFS Traversal:")
bfs(graph, 'A')
OUTPUT :
Practical No. 06
Aim : Write a program to implement Dijkstra’s shortest path algorithm using
Python language

CODE:

import heapq

def dijkstra(graph, start):

# Distance to all nodes is initially set to infinity

shortest_distances = {node: float('inf') for node in graph}

shortest_distances[start] = 0 # Distance to the start node is 0

# Priority queue to select the node with the smallest distance

priority_queue = [(0, start)]

while priority_queue:

current_distance, current_node = heapq.heappop(priority_queue)

# Skip if we've already found a better path

if current_distance > shortest_distances[current_node]:

continue

# Explore neighbors

for neighbor, weight in graph[current_node].items():


distance = current_distance + weight

# If a shorter path is found

if distance < shortest_distances[neighbor]:

shortest_distances[neighbor] = distance

heapq.heappush(priority_queue, (distance, neighbor))

return shortest_distances

# Example graph represented as an adjacency list with weights

graph = {

'A': {'B': 1, 'C': 4},

'B': {'C': 2, 'D': 5},

'C': {'D': 1},

'D': {}

# Find shortest paths from node 'A'

shortest_paths = dijkstra(graph, 'A')

# Display the shortest distances

print("Shortest distances from node 'A':")


OUTPUT:
Practical No. 07
Aim : Implementation of convolutional neural network to predict numbers

CODE:
from number images from keras.datasets import
mnist from keras.utils import to_categorical from
keras.models import Sequential from
keras.layers import Dense,Conv2D,Flatten
import matplotlib.pyplot as plt
#download mnist data and split into train and test sets
(X_train,Y_train),(X_test,Y_test)=mnist.load_data()
#plot the first image in the dataset
plt.imshow(X_train[0]) plt.show()
print(X_train[0].shape)
X_train=X_train.reshape(60000,28,28,1)
X_test=X_test.reshape(10000,28,28,1)
Y_train=to_categorical(Y_train)
Y_test=to_categorical(Y_test)
Y_train[0]
print(Y_train[0])
model=Sequential()
#add model layers #learn
image features
model.add(Conv2D(64,kernel_size=3,activation='relu',input_shape=(28,28,1)))
model.add(Conv2D(32,kernel_size=3,activation='relu')) model.add(Flatten())
model.add(Dense(10,activation='softmax'))
model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['accuracy'])
#train
model.fit(X_train,Y_train,validation_data=(X_test,Y_test),epochs=3)
print(model.predict(X_test[:4]))
#actual results for 1st 4 images in the test set print(Y_test[:4])
OUTPUT:

Pridicted Numbers Are (28, 28)


Neaural Network Series Of 28 & 29 Are [0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
Practical No. 08
Aim : Implementing regularization to avoid overfitting in binary classification.

CODE:
from matplotlib import pyplot from
sklearn.datasets import make_moons from
keras.models import Sequential from
keras.layers import Dense
X,Y=make_moons(n_samples=100,noise=0.2,random_state=1) n_train=30
trainX,testX=X[:n_train,:],X[n_train:] trainY,testY=Y[:n_train],Y[n_train:]
#print(trainX)
#print(trainY)
#print(testX) #print(testY)
model=Sequential()
model.add(Dense(500,input_dim=2,activation='relu'))
model.add(Dense(1,activation='sigmoid'))
model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])
history=model.fit(trainX,trainY,validation_data=(testX,testY),epochs=4000)
pyplot.plot(history.history['accuracy'],label='train')
pyplot.plot(history.history['val_accuracy'],label='test') pyplot.legend()
pyplot.show()
OUTPUT :

You might also like