Experiment No.
1
Matrix Operations – Addition, Subtraction, Multiplication
Python Program:
import numpy as np
# Define two matrices
A = [Link]([[1, 2],
[3, 4]])
B = [Link]([[5, 6],
[7, 8]])
# Matrix Addition
add_result = A + B
# Matrix Subtraction
sub_result = A - B
# Matrix Multiplication (Dot Product)
mul_result = A @ B # or [Link](A, B)
# Display the results
print("Matrix A:")
print(A)
print("\nMatrix B:")
print(B)
print("\nMatrix Addition (A + B):")
print(add_result)
print("\nMatrix Subtraction (A - B):")
print(sub_result)
print("\nMatrix Multiplication (A x B):")
print(mul_result)
Output:
Matrix A:
[[1 2]
[3 4]]
Matrix B:
[[5 6]
[7 8]]
Matrix Addition (A + B):
[[ 6 8]
[10 12]]
Matrix Subtraction (A - B):
[[-4 -4]
[-4 -4]]
Matrix Multiplication (A x B):
[[19 22]
[43 50]]
Experiment No. 2
Minimum Cost Path Problem
Goal: Find the path from the top-left to the bottom-right of a cost matrix such that the sum of the
path's cost is minimized. You can only move right or down.
Python Program:
def min_cost_path(cost):
m, n = len(cost), len(cost[0])
dp = [[0] * n for _ in range(m)]
dp[0][0] = cost[0][0]
# Initialize first row and column
for i in range(1, m):
dp[i][0] = dp[i-1][0] + cost[i][0]
for j in range(1, n):
dp[0][j] = dp[0][j-1] + cost[0][j]
# Fill the rest of the dp table
for i in range(1, m):
for j in range(1, n):
dp[i][j] = cost[i][j] + min(dp[i-1][j], dp[i][j-1])
return dp[m-1][n-1]
# Sample cost matrix
cost_matrix = [
[1, 2, 3],
[4, 8, 2],
[1, 5, 3]
# Calculate and print the result
result = min_cost_path(cost_matrix)
print("Minimum Cost to reach bottom-right corner:", result)
Output:
Minimum Cost to reach bottom-right corner: 11
Experiment No. 3
Finding Maximum Number In An Array
Python Program:
# Define an array
arr = [12, 45, 7, 89, 23, 56, 91, 14]
# Initialize max_num with the first element
max_num = arr[0]
# Loop through the array to find the maximum
for num in arr:
if num > max_num:
max_num = num
# Display the result
print("Array:", arr)
print("Maximum Number in the Array:", max_num)
Output:
Array: [12, 45, 7, 89, 23, 56, 91, 14]
Maximum Number in the Array: 91
Experiment No. 4
Array Sorting
Sorting an array in ascending order using both:
1. Python’s built-in sort() method
2. A manual sorting method (Bubble Sort)
Array Sorting – Python Program
Method 1: Using Built-in sort()
# Define the array
arr = [34, 12, 5, 66, 2, 89, 21]
# Sort the array
[Link]()
# Display the sorted array
print("Sorted Array (Using sort()):", arr)
Method 2: Manual Sorting (Bubble Sort)
# Define the array
arr = [34, 12, 5, 66, 2, 89, 21]
# Bubble Sort Algorithm
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
# Display the sorted array
print("Sorted Array (Using Bubble Sort):", arr)
Output:
Sorted Array (Using sort()): [2, 5, 12, 21, 34, 66, 89]
Sorted Array (Using Bubble Sort): [2, 5, 12, 21, 34, 66, 89]
Experiment No. 5
Linear Programming Problem (LPP)
Problem Statement (Example)
Python Program:
from [Link] import linprog
# Coefficients of the objective function (for maximization, use negative values)
c = [-3, -2] # Maximize 3x + 2y → Minimize -3x - 2y
# Coefficients of the inequality constraints (left-hand side)
A=[
[1, 2],
[4, 0],
[0, 4]
]
# Right-hand side of the inequality constraints
b = [8, 16, 12]
# Bounds for x and y (non-negative)
x_bounds = (0, None)
y_bounds = (0, None)
# Solve the linear program
res = linprog(c, A_ub=A, b_ub=b, bounds=[x_bounds, y_bounds], method='highs')
# Display results
if [Link]:
print("Optimal Value of Z:", -[Link])
print("Values of x and y:", res.x)
else:
print("Linear program did not find a solution.")
Output:
Optimal Value of Z: 12.0
Values of x and y: [4. 2.]
Experiment No. 6
Queuing Problem
Queuing Theory – M/M/1 Queue
Assumptions:
• Poisson arrivals and exponential service times.
• Single server.
• Infinite queue length.
Formulas Used (M/M/1)
Python Program:
# Input values
arrival_rate = 2.0 # λ (e.g. 2 customers per minute)
service_rate = 3.0 # μ (e.g. 3 customers per minute)
# Check system stability
if arrival_rate >= service_rate:
print("System is unstable. Arrival rate must be less than service rate.")
else:
# Calculations
rho = arrival_rate / service_rate
L = arrival_rate / (service_rate - arrival_rate)
Lq = (arrival_rate ** 2) / (service_rate * (service_rate - arrival_rate))
W = 1 / (service_rate - arrival_rate)
Wq = arrival_rate / (service_rate * (service_rate - arrival_rate))
# Display results
print("Queuing System (M/M/1):")
print(f"Utilization (ρ): {rho:.2f}")
print(f"Average number in system (L): {L:.2f}")
print(f"Average number in queue (Lq): {Lq:.2f}")
print(f"Average time in system (W): {W:.2f} minutes")
print(f"Average time in queue (Wq): {Wq:.2f} minutes")
Output:
Queuing System (M/M/1):
Utilization (ρ): 0.67
Average number in system (L): 2.00
Average number in queue (Lq): 1.33
Average time in system (W): 1.00 minutes
Average time in queue (Wq): 0.67 minutes
Experiment No. 7
Sequencing Problem
Sequencing Problem using Johnson’s Rule, which is commonly used for 2 machines and n
jobs to minimize total processing time.
Sequencing Problem – Johnson's Algorithm (2 Machines)
Given:
• A list of jobs with processing times on Machine 1 and Machine 2.
Goal:
• Find the optimal sequence that minimizes total completion time.
Python Program:
def johnsons_algorithm(jobs):
n = len(jobs)
sequence = []
left = []
right = []
# Jobs format: (job_id, machine1_time, machine2_time)
remaining_jobs = [Link]()
while remaining_jobs:
# Find job with minimum processing time
min_job = min(remaining_jobs, key=lambda x: min(x[1], x[2]))
remaining_jobs.remove(min_job)
if min_job[1] < min_job[2]:
[Link](min_job)
else:
[Link](0, min_job) # insert at front
sequence = left + right
return sequence
# Example jobs: (job_id, M1 time, M2 time)
jobs = [
(1, 3, 5),
(2, 2, 1),
(3, 4, 6),
(4, 6, 3),
(5, 1, 2)
# Get optimal sequence
optimal_sequence = johnsons_algorithm(jobs)
# Display results
print("Optimal Job Sequence (Job ID):")
print([job[0] for job in optimal_sequence])
Output:
Optimal Job Sequence (Job ID):
[5, 2, 1, 3, 4]
Experiment No. 8
Game Theory
A Game Theory problem for 2-player zero-sum games with a payoff matrix, using
the minimax and maximin strategies.
Game Theory – Two Player Zero-Sum Game (Pure Strategy)
We’ll compute:
• Row player's maximin
• Column player's minimax
• If both values are equal → Saddle point exists, and the game has a pure strategy
solution.
Python Program:
import numpy as np
# Payoff matrix (Row player)
payoff_matrix = [Link]([
[3, 6],
[5, 1]
])
# Maximin (for Row player)
row_minima = [Link](payoff_matrix, axis=1)
maximin = [Link](row_minima)
# Minimax (for Column player)
col_maxima = [Link](payoff_matrix, axis=0)
minimax = [Link](col_maxima)
# Display
print("Payoff Matrix:")
print(payoff_matrix)
print("\nRow Minima:", row_minima)
print("Maximin (Row player):", maximin)
print("\nColumn Maxima:", col_maxima)
print("Minimax (Column player):", minimax)
# Saddle point check
if maximin == minimax:
print("\nSaddle point exists! Pure strategy optimal value:", maximin)
else:
print("\nNo saddle point. Mixed strategy needed.")
Output:
Payoff Matrix:
[[3 6]
[5 1]]
Row Minima: [3 1]
Maximin (Row player): 3
Column Maxima: [5 6]
Minimax (Column player): 5
No saddle point. Mixed strategy needed.
Experiment No. 9
Assignment Problem
Assignment Problem using the Hungarian Algorithm, which is available via
[Link].linear_sum_assignment.
Assignment Problem (Hungarian Algorithm)
Goal: Minimize total cost of assigning n workers to n jobs such that each worker gets one job.
Python Program:
import numpy as np
from [Link] import linear_sum_assignment
# Cost matrix (rows: workers, columns: jobs)
cost_matrix = [Link]([
[9, 2, 7, 8],
[6, 4, 3, 7],
[5, 8, 1, 8],
[7, 6, 9, 4]
])
# Apply Hungarian Algorithm
row_ind, col_ind = linear_sum_assignment(cost_matrix)
# Calculate total cost
total_cost = cost_matrix[row_ind, col_ind].sum()
# Display assignments and cost
print("Assignment Results:")
for i in range(len(row_ind)):
print(f"Worker {row_ind[i]} assigned to Job {col_ind[i]} with cost {cost_matrix[row_ind[i],
col_ind[i]]}")
print("\nTotal Minimum Cost:", total_cost)
Output:
Assignment Results:
Worker 0 assigned to Job 1 with cost 2
Worker 1 assigned to Job 2 with cost 3
Worker 2 assigned to Job 0 with cost 5
Worker 3 assigned to Job 3 with cost 4
Total Minimum Cost: 14
Experiment No. 10
Dynamic Programming Problem
A classic Dynamic Programming Problem: the 0/1 Knapsack Problem.
Dynamic Programming – 0/1 Knapsack Problem
Problem:
Given n items with weights and values, find the maximum value that fits in a knapsack of
capacity W, where each item can be included at most once.
Python Program:
def knapsack(weights, values, capacity):
n = len(weights)
# Create DP table: (n+1) x (capacity+1)
dp = [[0 for _ in range(capacity + 1)] for _ in range(n + 1)]
# Build the table dp[][] in bottom-up manner
for i in range(1, n + 1):
for w in range(1, capacity + 1):
if weights[i-1] <= w:
dp[i][w] = max(values[i-1] + dp[i-1][w - weights[i-1]], dp[i-1][w])
else:
dp[i][w] = dp[i-1][w]
return dp[n][capacity]
# Example items
values = [60, 100, 120]
weights = [10, 20, 30]
capacity = 50
# Call the function and print result
max_value = knapsack(weights, values, capacity)
print("Maximum value in Knapsack:", max_value)
Output:
Maximum value in Knapsack: 220
Experiment No. 11
Inventory Problem
A basic Inventory Management Problem using the Economic Order Quantity (EOQ) Model.
Inventory Problem – EOQ Model
Objective: Minimize the total inventory cost by calculating the optimal order quantity.
Python Program:
import math
def calculate_eoq(D, S, H):
eoq = [Link]((2 * D * S) / H)
return eoq
# Example input values
annual_demand = 1000 # D: units/year
ordering_cost = 50 # S: ₹ per order
holding_cost = 2 # H: ₹ per unit per year
# Calculate EOQ
eoq = calculate_eoq(annual_demand, ordering_cost, holding_cost)
# Display result
print("Economic Order Quantity (EOQ):", round(eoq, 2))
Output:
Economic Order Quantity (EOQ): 223.61
Experiment No. 12
Examinations
Managing Examinations, which includes:
• Storing student names and their marks for different subjects
• Calculating total and average marks
• Finding topper(s)
• Displaying all student records in a clean format
Python Program – Examination Marks Management
# List to store student data
students = []
# Number of students and subjects
num_students = int(input("Enter number of students: "))
num_subjects = int(input("Enter number of subjects: "))
# Input subject names
subject_names = []
for i in range(num_subjects):
subject = input(f"Enter name of subject {i+1}: ")
subject_names.append(subject)
# Input student data
for i in range(num_students):
name = input(f"\nEnter name of student {i+1}: ")
marks = []
for subject in subject_names:
score = float(input(f"Enter marks in {subject}: "))
[Link](score)
total = sum(marks)
average = total / num_subjects
[Link]({
"name": name,
"marks": marks,
"total": total,
"average": average
})
# Find topper
topper = max(students, key=lambda x: x['total'])
# Display Results
print("\n----- Examination Results ----- ")
for student in students:
print(f"\nName: {student['name']}")
for i, mark in enumerate(student['marks']):
print(f"{subject_names[i]}: {mark}")
print(f"Total: {student['total']}")
print(f"Average: {student['average']:.2f}")
print(f"\nTopper: {topper['name']} with {topper['total']} marks")
Output:
Enter number of students: 2
Enter number of subjects: 3
Enter name of subject 1: Math
Enter name of subject 2: Physics
Enter name of subject 3: Chemistry
Enter name of student 1: Alice
Enter marks in Math: 85
Enter marks in Physics: 90
Enter marks in Chemistry: 88
Enter name of student 2: Bob
Enter marks in Math: 78
Enter marks in Physics: 82
Enter marks in Chemistry: 79
----- Examination Results -----
Name: Alice
Math: 85.0
Physics: 90.0
Chemistry: 88.0
Total: 263.0
Average: 87.67
Name: Bob
Math: 78.0
Physics: 82.0
Chemistry: 79.0
Total: 239.0
Average: 79.67
Topper: Alice with 263.0 marks