0% found this document useful (0 votes)
18 views16 pages

Ot Lab - 1-12

The document contains a series of Python programs that demonstrate various algorithmic concepts including matrix operations, minimum cost path, finding maximum numbers in arrays, sorting, linear programming, queuing problems, sequencing, game theory, assignment problems, dynamic programming for knapsack, matrix chain multiplication, and inventory problems. Each program is accompanied by source code and expected output. The programs utilize libraries such as NumPy, SciPy, and PuLP for mathematical computations.

Uploaded by

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

Ot Lab - 1-12

The document contains a series of Python programs that demonstrate various algorithmic concepts including matrix operations, minimum cost path, finding maximum numbers in arrays, sorting, linear programming, queuing problems, sequencing, game theory, assignment problems, dynamic programming for knapsack, matrix chain multiplication, and inventory problems. Each program is accompanied by source code and expected output. The programs utilize libraries such as NumPy, SciPy, and PuLP for mathematical computations.

Uploaded by

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

Question No.1: Write a python program for Matrix Operations.

Source Code:
import numpy as np
mx1 = np.array([[5, 10], [15, 20]])
mx2 = np.array([[25, 30], [35, 40]])
print("Matrix1 =\n",mx1) print("\
nMatrix2 =\n",mx2)
print ("\nAddition of two matrices: ")
print (np.add(mx1,mx2))
print ("\nSubtraction of two matrices:
") print (np.subtract(mx1,mx2))
print ("\nMatrix Division: ")
print (np.divide(mx1,mx2))
print ("\nMultiplication of two matrices: ")
print (np.multiply(mx1,mx2))
Output:
Question No.2: Write a python program for Min Cost Path.
Source Code:
R=3
C=3
def minCost(cost, m, n):
# initialization
tc = [[0 for x in range(C)] for x in
range(R)] # base case
tc[0][0] = cost[0][0]
# total cost(tc) array
for i in range(1, m + 1):
tc[i][0] = tc[i-1][0] + cost[i]
[0] for j in range(1, n + 1):
tc[0][j] = tc[0][j-1] + cost[0]
[j] for i in range(1, m + 1):
for j in range(1, n + 1):
tc[i][j] = min(tc[i-1][j-1], tc[i-1][j], tc[i][j-1]) + cost[i][j]
return tc[m][n]
cost = [[1, 5, 3],
[7, 7, 4],
[8, 5, 3]]
print("Total Cost:",minCost(cost, 2, 1))
Output:
Question No.3: Write a python program for Finding Maximum Number in An
Array.
Source Code:
def myMax(list1):
max = list1[0]
for x in list1:
if x > max:
max = x
return max
list1 = [10, 20, 4, 45, 99]
print("Largest element is:", myMax(list1))
Output:

Question No.4: Write a python program Array Sorting.


Source Code:
import array as arr
orgnlArray = arr.array('i', [10,5,15,4,6,20,9])
print("Original array:", orgnlArray)
sortedList = orgnlArray.tolist()
sortedList.sort()
sortedArray = arr.array('i', sortedList)
print("Array after sorting:",sortedArray)
Output:
Question No.5: Write a python program for Linear Programming Problem (LLP):

Source Code with Output:


import pulp as p
Lp_prob = p.LpProblem('Problem1', p.LpMaximize)
#Decision Variables
x1 = p.LpVariable("x1", lowBound = 0) # Create a variable x1 >=
0 x2 = p.LpVariable("x2", lowBound = 0) # Create a variable x2
>= 0 x3 = p.LpVariable("x3", lowBound = 0) # Create a variable
x3 >= 0 #Objective Function
Lp_prob += 1600*x1 + 1300*x2 + 600*x3
#Constraints
Lp_prob += 2*x1 + 1.5*x2 + x3 <=
20 Lp_prob += 2*x1 + x2 + 1.5*x3
<= 24 Lp_prob += x1 + 2*x2 +
0.5*x3 <= 20 print(Lp_prob)
#Solving the LPP
status = Lp_prob.solve()
print(p.LpStatus[status])

#Solution
print("x1 =", p.value(x1))
print("x2 =", p.value(x2))
print("x3 =", p.value(x3))
print("Objective = ", p.value(Lp_prob.objective))

Question No.6: Write a python program for Queuing Problem (QP) on Simulating
Bank Queues.
Source Code:
import numpy as np
import matplotlib.pyplot as plt
# Function to simulate the bank queue
def simulate_bank_queue(num_tellers, arrival_rate, service_rate, sim_time):
# Initialize variables
time = 0
queue_length = []
wait_times = []

# Initialize empty lists for arrival and service times


arrival_times = []
service_times = []

# Simulate until sim_time


while time < sim_time:
# Generate inter-arrival time and update time
inter_arrival_time = np.random.exponential(1 / arrival_rate)
time += inter_arrival_time

# Generate service time


service_time = np.random.exponential(1 / service_rate)
# Update arrival and service times lists
arrival_times.append(time)
service_times.append(service_time)

# Calculate wait time


if len(arrival_times) <= num_tellers:
wait_time = max(0, time - service_times[len(arrival_times) - 1])
else:
wait_time = max(0, time - arrival_times[len(arrival_times) - num_tellers - 1])
# Update wait times list
wait_times.append(wait_time)
# Update queue length
queue_length.append(len(arrival_times) -
num_tellers) return queue_length, wait_times
# Parameters
NUM_TELLERS = 3
ARRIVAL_RATE = 20 # customers per hour
SERVICE_RATE = 25 # customers per hour
SIM_TIME = 8 * 60 # 8 hours
# Run simulation
queue_length, wait_times = simulate_bank_queue(NUM_TELLERS, ARRIVAL_RATE,
SERVICE_RATE, SIM_TIME)

# Calculate average wait time


avg_wait_time = np.mean(wait_times)
print(f"Average wait time: {avg_wait_time:.2f} minutes")

# Plot queue length over time


plt.figure(figsize=(10, 6))
plt.plot(np.arange(len(queue_length)), queue_length)
plt.title("Queue Length Over Time")
plt.xlabel("Time (minutes)")
plt.ylabel("Queue Length")
plt.grid(True)
plt.show()
Output:

Question No.7: Write a python program for Sequencing Problem (SP).


Source Code:
def printJobScheduling(arr, t):
# length of array
n = len(arr)
# Sort all jobs according to decreasing order of profit
for i in range(n):
for j in range(n - 1 - i):
if arr[j][2] < arr[j + 1][2]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
# To keep track of free time slots
result = [False] * t
# To store result (Sequence of jobs)
job = ['-1'] * t
# Iterate through all given jobs
for i in range(len(arr)):
# Find a free slot for this job
# (Note that we start from the last possible slot)
for j in range(min(t - 1, arr[i][1] - 1), -1, -1):
# Free slot found
if result[j] is False:
result[j] =
True job[j] =
arr[i][0] break
# print the sequence
print(job)

# Driver's Code
if name == ' main ':
arr = [['a', 2, 100], # Job Array
['b', 1, 19],
['c', 2, 27],
['d', 1, 25],
['e', 3, 15]]
print("Following is maximum profit sequence of jobs")
# Function Call
printJobScheduling(arr, 3)
Output:
Question No.8: Write a python program for Game Theory.
Source Code:
import numpy as np
from scipy.optimize import linprog
# Define the payoff matrix for player 1
payoff_matrix_p1 = np.array([[3, 0],
[5, 1]])
# Define the payoff matrix for player 2 (transpose of player 1 matrix)
payoff_matrix_p2 = np.array([[3, 5],
[0, 1]])
# Function to calculate Nash equilibrium using linear programming
def nash_equilibrium(payoff_matrix):
num_strategies =
payoff_matrix.shape[0]
# Objective function: maximize the minimum value (minimax strategy)
c = [-1] * num_strategies # Minimize the negative value
# Constraints: probabilities must sum to 1, and each probability should
be non-negative
A_eq = np.ones((1, num_strategies))
b_eq = [1]
# Bounds for probabilities: each should be between 0 and 1
bounds = [(0, 1) for _ in range(num_strategies)]
# Solve the linear programming problem
res = linprog(c, A_eq=A_eq, b_eq=b_eq, bounds=bounds)
if res.success:
return res.x
else:
return None
# Get Nash equilibrium for player 1 and player 2
nash_p1 = nash_equilibrium(payoff_matrix_p1)
nash_p2 = nash_equilibrium(payoff_matrix_p2.T)

print("Nash Equilibrium for Player 1:",


nash_p1) print("Nash Equilibrium for Player
2:", nash_p2) Output:

Question No.9: Write a python program for Assignment Problem.


Source Code:
from ortools.linear_solver import
pywraplp def main():
# Data
costs = [
[90, 80, 75, 70],
[35, 85, 55, 65],
[125, 95, 90, 95],
[45, 110, 95, 115],
[50, 100, 90, 100],
]
num_workers = len(costs)
num_tasks = len(costs[0])
# Solver
# Create the mip solver with the SCIP backend.
solver = pywraplp.Solver.CreateSolver("SCIP")
if not solver:
return
# Variables
# x[i, j] is an array of 0-1 variables, which will be
1 # if worker i is assigned to task j.
x = {}
for i in range(num_workers):
for j in range(num_tasks):
x[i, j] = solver.IntVar(0, 1, "")

# Constraints
# Each worker is assigned to at most 1 task.
for i in range(num_workers):
solver.Add(solver.Sum([x[i, j] for j in range(num_tasks)]) <= 1)
# Each task is assigned to exactly one worker.
for j in range(num_tasks):
solver.Add(solver.Sum([x[i, j] for i in range(num_workers)]) == 1)
# Objective
objective_terms = []
for i in range(num_workers):
for j in range(num_tasks):
objective_terms.append(costs[i][j] * x[i, j])
solver.Minimize(solver.Sum(objective_terms))
# Solve
print(f"Solving with {solver.SolverVersion()}")
status = solver.Solve()
# Print solution
if status == pywraplp.Solver.OPTIMAL or status == pywraplp.Solver.FEASIBLE:
print(f"Total cost = {solver.Objective().Value()}\n")
for i in range(num_workers):
for j in range(num_tasks):
# Test if x[i,j] is 1 (with tolerance for floating point arithmetic).
if x[i, j].solution_value() > 0.5:
print(f"Worker {i} assigned to task {j}." + f" Cost: {costs[i][j]}")
else:
print("No solution found.")
if name == " main ":
main()
Output:

Question No.10: Write a python program for Dynamic Programming on 0-1


knapsack problem.
Source Code:
import sys
def knapsack(v, w, n, W, lookup):
if W < 0:
return -sys.maxsize
if n < 0 or W == 0:
return 0

key = (n, W)
if key not in lookup:
include = v[n] + knapsack(v, w, n - 1, W - w[n],
lookup) exclude = knapsack(v, w, n - 1, W, lookup)
lookup[key] = max(include, exclude)
return lookup[key]

if name == ' main ':


v = [20, 5, 10, 40, 15, 25]
w = [1, 2, 3, 8, 7, 4]
W = 10
lookup = {}
print('Knapsack value is', knapsack(v, w, len(v) - 1, W, lookup))
Output:

Question No.11: Write a python program on Matrix Chain Multiplication using


Dynamic Programming.
Source Code:
import sys
def matrixChainMultiplication(dims, i, j):
if j <= i + 1:
return 0
min = sys.maxsize
(M[i+1]) × (M[i+2]...................M[j])
(M[i+1]M[i+2]) × (M[i+3.............M[j])


(M[i+1]M[i+2]…..........M[j-1]) × (M[j])
'''
for k in range(i + 1, j):

cost = matrixChainMultiplication(dims, i, k)
cost += matrixChainMultiplication(dims, k, j)

cost += dims[i] * dims[k] * dims[j]


if cost < min:
min = cost
return min

if name == ' main ':


dims = [10, 30, 5, 60]
print('The minimum cost is', matrixChainMultiplication(dims, 0, len(dims) - 1))
Output:

Question No.12: Write a python program for Inventory Problem.


Source Code:
import math
def eoq(demand, ordering_cost, holding_cost):
eoq_value = math.sqrt((2 * demand * ordering_cost) / holding_cost)
return eoq_value
def total_cost(eoq_value, demand, ordering_cost, holding_cost):

num_orders = demand / eoq_value


total_ordering_cost = num_orders * ordering_cost
avg_inventory = eoq_value / 2
total_holding_cost = avg_inventory * holding_cost
total_cost_value = total_ordering_cost + total_holding_cost
return total_cost_value

demand = 5000 # Annual demand (units)


ordering_cost = 100 # Ordering cost per order ($)
holding_cost = 2 # Holding cost per unit per year
($)

eoq_value = eoq(demand, ordering_cost, holding_cost)


print(f"Economic Order Quantity (EOQ): {eoq_value:.2f} units")
total_cost_value = total_cost(eoq_value, demand, ordering_cost, holding_cost)
print(f"Total Inventory Cost: ${total_cost_value:.2f}")
Output:

You might also like