Assignment 1 
 Logistics Network Dataset Creation

import pandas as pd

df = pd.read_csv("ASSIGNMENT_1.csv")
df.head(10)

Graph Construction Using Adjacency List 

from collections import defaultdict
import pandas as pd

# Read CSV file
df = pd.read_csv("ASSIGNMENT_1.csv")

# Create adjacency list
graph = defaultdict(list)

# Build graph
for _, row in df.iterrows():
    src = row['Source']
    dest = row['Destination']   # Make sure column name matches exactly

    graph[src].append(dest)
    graph[dest].append(src)   # Undirected graph

# Print adjacency list
for node in graph:
    print(node, "->", graph[node])

Recursive DFS Traversal

def dfs_recursive(graph, node, visited=None):
    if visited is None:
        visited = set()

    visited.add(node)
    print(node, end=" ")

    for neighbour in graph[node]:
        if neighbour not in visited:
            dfs_recursive(graph, neighbour, visited)


# Start DFS from first node in graph
start_node = list(graph.keys())[0]

print("DFS Recursive Traversal:")
dfs_recursive(graph, start_node)


 Non-Recursive DFS Using Stack

def dfs_iterative(graph, start):
    visited = set()
    stack = [start]

    print("DFS Iterative Traversal:")

    while stack:
        node = stack.pop()

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

            # Reverse to maintain similar order as recursive DFS
            stack.extend(reversed(graph[node]))


# Use same starting node
start_node = list(graph.keys())[0]
dfs_iterative(graph, start_node)


Route Availability Check

def route_exists_dfs(graph, source, destination, visited=None):
    if visited is None:
        visited = set()

    # If source equals destination → route found
    if source == destination:
        return True

    visited.add(source)

    for neighbour in graph[source]:
        if neighbour not in visited:
            if route_exists_dfs(graph, neighbour, destination, visited):
                return True

    return False


# Take input
src = input("Enter source hub: ")
dest = input("Enter destination hub: ")

# Check route
if route_exists_dfs(graph, src, dest):
    print(f"Route exists between {src} and {dest}")
else:
    print(f"No route exists between {src} and {dest}")


Identify Isolated Warehouses


isolated_hubs = []

for hub in graph:
    if len(graph[hub]) == 0:
        isolated_hubs.append(hub)

print("Isolated Warehouses / Hubs:")
print(isolated_hubs)


Connected Components in Logistics Network

def connected_components(graph):
    visited = set()
    components = []

    for hub in graph:
        if hub not in visited:
            stack = [hub]
            component = []

            while stack:
                node = stack.pop()

                if node not in visited:
                    visited.add(node)
                    component.append(node)

                    # Add neighbors to stack
                    stack.extend(graph[node])

            components.append(component)

    return components


# Get components
components = connected_components(graph)

print("Components in Logistics Network:")
for i, comp in enumerate(components, 1):
    print(f"Component {i}: {comp}")

print("Total number of connected components:", len(components))


 Simulating Route Failure

import copy

# Choose edge to remove
u = input("Enter first hub of failed route: ")
v = input("Enter second hub of failed route: ")

# Perform DFS before failure
print("\nDFS Traversal Before Route Failure:")
dfs_recursive(graph, start_node)

# Create a deep copy of the graph
graph_failed = copy.deepcopy(graph)

# Remove route if it exists
if u in graph_failed and v in graph_failed[u]:
    graph_failed[u].remove(v)
    graph_failed[v].remove(u)
    print(f"\nRemoved route between {u} and {v}")
else:
    print("\nRoute does not exist in graph.")

# Perform DFS after failure
print("\nDFS Traversal After Route Failure:")
dfs_recursive(graph_failed, start_node)


Detect Cycles in Logistics Routes

def detect_cycle(graph):
    visited = set()

    def dfs(node, parent):
        visited.add(node)

        for neighbour in graph[node]:
            if neighbour not in visited:
                if dfs(neighbour, node):
                    return True
            elif neighbour != parent:
                return True   # Cycle detected

        return False

    for hub in graph:
        if hub not in visited:
            if dfs(hub, None):
                return True

    return False


# Check for cycle
if detect_cycle(graph):
    print("Cycle detected in logistics network")
else:
    print("No cycle detected in logistics network")


Exploratory Data Analysis (EDA)

import pandas as pd

# Load dataset
marks_df = pd.read_csv("student marks.csv")

# Calculate statistics
mean = marks_df.mean(numeric_only=True)
median = marks_df.median(numeric_only=True)
mode = marks_df.mode().iloc[0]
std_dev = marks_df.std(numeric_only=True)

print("Mean:\n", mean)
print("\nMedian:\n", median)
print("\nMode:\n", mode)
print("\nStandard Deviation:\n", std_dev)

# Subject with highest average
print("\nSubject with highest average score:")
print(mean.idxmax())

 Correlation and Heatmap

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# Load customer dataset
cust_df = pd.read_csv("customer_data.csv")

# Compute correlation matrix (only numeric columns)
correlation_matrix = cust_df.corr(numeric_only=True)

print("Correlation Matrix:\n")
print(correlation_matrix)

# Plot heatmap
plt.figure(figsize=(8, 6))
sns.heatmap(correlation_matrix, annot=True, cmap="coolwarm")
plt.title("Correlation Heatmap")
plt.show()

Missing Value Analysis
import pandas as pd

# Load dataset with missing values
missing_df = pd.read_csv("missing_values.csv")

# Detect missing values
print("Missing values in each column:\n")
print(missing_df.isnull().sum())

# Replace missing values using mean (only numeric columns)
missing_df_filled = missing_df.fillna(missing_df.mean(numeric_only=True))

print("\nDataset after replacing missing values:\n")
print(missing_df_filled)






assignment 2

BFS and Best-First Search for Social Media Recommendations

 Creation of Social Media Network Dataset 

import pandas as pd

# Create DataFrame
df = pd.DataFrame(data)

# Save to CSV file
df.to_csv("output.csv", index=False)

# Display first 10 records
print("First 10 Records:\n", df.head(10))


Graph Representation from CSV Data 

from collections import defaultdict

graph = defaultdict(list)

# Build adjacency list
for _, row in df.iterrows():
    user1 = row["User1"]
    user2 = row["User2"]
    weight = row["Weight"]

    graph[user1].append((user2, weight))
    graph[user2].append((user1, weight))   # Undirected graph

# Print adjacency list
print("\nAdjacency List:")
for user in graph:
    print(user, "->", graph[user])

BFS Traversal of Social Network

from collections import deque

def bfs_traversal(graph, start):
    visited = set()
    queue = deque([start])
    order = []

    while queue:
        node = queue.popleft()

        if node not in visited:
            visited.add(node)
            order.append(node)

            for neighbor, weight in graph[node]:  # unpack tuple
                if neighbor not in visited:
                    queue.append(neighbor)

    return order


print("Traversal from A:")
print(bfs_traversal(graph, "A"))

BFS-Based Friend Recommendation

from collections import deque

def bfs_recommend(graph, start):
    visited = set([start])
    queue = deque([(start, 0)])
    recommendations = set()

    while queue:
        node, level = queue.popleft()

        if level == 2:
            recommendations.add(node)

        if level < 2:
            for neighbor, weight in graph[node]:  # weighted graph
                if neighbor not in visited:
                    visited.add(neighbor)
                    queue.append((neighbor, level + 1))

    return recommendations


print("Friend Recommendations from A:")
print(bfs_recommend(graph, "A"))


Shortest Connection Path Using BFS 

from collections import deque

def bfs_shortest_path(graph, start, end):
    queue = deque([[start]])
    visited = set([start])

    while queue:
        path = queue.popleft()
        node = path[-1]

        if node == end:
            return path

        for neighbor, weight in graph[node]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(path + [neighbor])

    return None


print("Path from A to H:")
print(bfs_shortest_path(graph, "A", "H"))


Implementation of Best-First Search

import heapq

def best_first_search(graph, start):
    visited = set()
    pq = [(0, start)]   # (priority, node)
    order = []

    while pq:
        priority, node = heapq.heappop(pq)

        if node not in visited:
            visited.add(node)
            order.append(node)

            for neighbor, weight in graph[node]:
                if neighbor not in visited:
                    heapq.heappush(pq, (weight, neighbor))

    return order


print("Traversal from A:")
print(best_first_search(graph, "A"))


Best-First Search Based Recommendation 

import heapq

def best_first_recommend(graph, start):
    visited = set([start])
    pq = []
    recommendations = []

    # Push direct neighbors into priority queue (max weight first)
    for neighbor, weight in graph[start]:
        heapq.heappush(pq, (-weight, neighbor))  # negative for max-heap behavior

    while pq and len(recommendations) < 5:
        priority, node = heapq.heappop(pq)

        if node not in visited:
            visited.add(node)
            recommendations.append(node)

    return recommendations


print("\nBest-First Recommendation from A:")
print(best_first_recommend(graph, "A"))


Interactive Source and Destination Selection

# Take user input
src = input("\nEnter source user: ")
dst = input("Enter destination user: ")

# Find shortest path using BFS
path = bfs_shortest_path(graph, src, dst)

if path:
    print("Connection Exists:", path)
else:
    print("No Connection Found")

# Best-First Traversal
print("Best-First Traversal:")
print(best_first_search(graph, src))

Checking Connection Between Two Users

# Take user input
src = input("\nEnter source user: ")
dst = input("Enter destination user: ")

# Call shortest path function
path = bfs_shortest_path(graph, src, dst)

if path:
    print("Connection Exists:", path)
else:
    print("No Connection Found")

# Best First Traversal
print("Best-First Traversal:")
print(best_first_search(graph, src))


Influencer Identification Using BFS and Best-First Search 

def influencers (graph) :
scores = { }
for user in graph:
scores[user] = len(bfs_traversal(graph,
user) )
return sorted(scores.items(), key—lambda x:
x[l], reverse=True)
print("\nTop Influencers
influencers (graph ) [ : 3] )

