SCA Practice Questions

Download as xlsx, pdf, or txt
Download as xlsx, pdf, or txt
You are on page 1of 34

Jan

Demand 1000

Regular Capacity 800


Overtime capacity 200
Actual OT produced 200
Total inventory 1000
Inventory left 0

Cost of production 16000


Cost of OT 5000

Holding cost 0

Obj function min cost 82100


PYTHON CODE
from scipy.optimize import linprog

# Costs
cost_regular = 20 # Cost per unit for regular production
cost_overtime = 25 # Cost per unit for overtime production
cost_holding = 3 # Holding cost per unit per month

# Monthly demands
demands = [1000, 800, 1200, 900] # Demands for January, February, March, and April

# Number of variables (3 per month - regular production, overtime production, inventory)


num_months = 4
num_vars = 3 * num_months

# Objective function coefficients (minimize cost)


c = [cost_regular, cost_overtime, cost_holding] * num_months

# Inequality constraints (A_ub @ x <= b_ub)


# Production capacity constraints for regular (800 units) and overtime (200 units) per each month
A_ub = [[1 if i == j * 3 else 0 for i in range(num_vars)] for j in range(num_months)] + \
[[1 if i == j * 3 + 1 else 0 for i in range(num_vars)] for j in range(num_months)]
b_ub = [800] * num_months + [200] * num_months

# Equality constraints (A_eq @ x = b_eq)


# Inventory balance and demand satisfaction
A_eq = [[0]*num_vars for _ in range(num_months)]
for month in range(num_months):
if month > 0:
A_eq[month][month*3-1] = 1 # Previous month's inventory
A_eq[month][month*3:month*3+2] = [1, 1] # Current month's regular and overtime production
A_eq[month][month*3+2] = -1 # Inventory held

b_eq = demands

# Bounds for decision variables (non-negativity)


bounds = [(0, None)] * num_vars

# Solve the linear programming problem


result = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=bounds, method='highs')

# Output the result


if result.success:
total_cost = result.fun
production_plan = result.x
else:
total_cost = "Optimization failed"
production_plan = None

total_cost, production_plan
Feb March April
800 1200 900

800 800 800


200 200 200
200 200 100
1000 1200 900
200 0 0

16000 16000 16000


5000 5000 2500

600 0 0
(82100.0,
array([800., 200., 0., 800., 200., 200., 800., 200., 0., 800.,
0.]))
To solve the Linear Programming (LP) problem using Excel Solver, follow these steps:

1. **Prepare Your Spreadsheet**:


- Open a new Excel workbook.
- Set up columns for each month (January to April). Label them appropriately.
- Create rows for the following: 'Regular Production', 'Overtime Production', 'Cost per Regular Unit', 'Cost per Overtime Unit'

2. **Input Data**:
- Enter the production capacity limits (800 for regular, 200 for overtime) in the respective rows.
- Input the costs (Rs. 20 for regular, Rs. 25 for overtime) in the 'Cost per Unit' rows.
- Enter the monthly demands (1000, 800, 1200, 900) in the 'Monthly Demand' row.

3. **Set Up Variables**:
- In the 'Regular Production' and 'Overtime Production' rows, input the initial guesses for production quantities. These will be

4. **Calculate Monthly and Total Costs**:


- For each month, calculate the 'Monthly Cost' as `(Regular Production * Cost per Regular Unit) + (Overtime Production * Cos
- Calculate the 'Total Cost' as the sum of all 'Monthly Costs'.

5. **Enable Solver**:
- Go to 'File' > 'Options' > 'Add-ins'.
- In the 'Manage' box, select 'Excel Add-ins' and click 'Go'.
- Check the box next to 'Solver Add-in' and click 'OK' to enable it.

6. **Configure Solver Parameters**:


- Click 'Data' on the ribbon, and then click 'Solver'.
- Set the 'Set Objective' box to the cell containing 'Total Cost'. Choose 'Min' for minimizing the cost.
- In 'By Changing Variable Cells', select the cells corresponding to 'Regular Production' and 'Overtime Production' for all mont
- Add 'Constraints':
- Regular Production <= 800 for each month.
- Overtime Production <= 200 for each month.
- Regular Production + Overtime Production = Monthly Demand for each month.
- Choose a solving method. The 'Simplex LP' method is suitable for linear problems.

7. **Run Solver**:
- Click 'Solve'. Solver will find the optimal solution based on your constraints.
- If Solver finds a solution, it will ask if you want to keep the solver solution or restore original values. Choose to keep the sol

8. **Review Results**:
- The cells for 'Regular Production' and 'Overtime Production' will be updated with the quantities that minimize the total cos
- Check the 'Total Cost' to see the minimum cost calculated by Solver.
, 200., 200., 800., 200., 0., 800., 100.,
line 1

line 2
Python code
pip install pulp

from pulp import *

# Define the problem


prob = LpProblem("Minimum_Cost_Staffing", LpMinimize)

# Variables for full-time and part-time consultants in each shift


ft_8_12 = LpVariable("FT_8_12", 0, cat='Integer') # full-time from 8 am to 12 pm
pt_8_12 = LpVariable("PT_8_12", 0, cat='Integer') # part-time from 8 am to 12 pm

ft_12_4 = LpVariable("FT_12_4", 0, cat='Integer') # full-time from 12 pm to 4 pm


pt_12_4 = LpVariable("PT_12_4", 0, cat='Integer') # part-time from 12 pm to 4 pm

ft_4_8 = LpVariable("FT_4_8", 0, cat='Integer') # full-time from 4 pm to 8 pm


pt_4_8 = LpVariable("PT_4_8", 0, cat='Integer') # part-time from 4 pm to 8 pm

ft_8_12am = LpVariable("FT_8_12AM", 0, cat='Integer') # full-time from 8 pm to 12 am


pt_8_12am = LpVariable("PT_8_12AM", 0, cat='Integer') # part-time from 8 pm to 12 am

# Cost per hour for full-time and part-time consultants


cost_ft = 14
cost_pt = 12

# Objective function: Minimize the total cost


prob += (ft_8_12 + ft_12_4 + ft_4_8 + ft_8_12am) * cost_ft * 8 + (pt_8_12 + pt_12_4 + pt_4_8 + pt_8_12am) * cost_pt * 4

# Constraints
# Minimum number of consultants required for each shift
prob += ft_8_12 + pt_8_12 >= 4
prob += ft_12_4 + pt_12_4 >= 8
prob += ft_4_8 + pt_4_8 >= 10
prob += ft_8_12am + pt_8_12am >= 6

# At least 2 full-time consultants for every part-time consultant on duty


prob += 2 * pt_8_12 <= ft_8_12
prob += 2 * pt_12_4 <= ft_12_4
prob += 2 * pt_4_8 <= ft_4_8
prob += 2 * pt_8_12am <= ft_8_12am
# Solve the problem
prob.solve()

# Output the results


for v in prob.variables():
print(v.name, "=", v.varValue)

# Print the total cost


print("Total Cost = $", value(prob.objective))
12am) * cost_pt * 4
Objective value: 2624.00000000
Enumerated nodes: 0
Total iterations: 3
Time (CPU seconds): 0.00
Time (Wallclock seconds): 0.03

Option for printingOptions changed from normal to all


Total time (CPU seconds): 0.00 (Wallclock seconds): 0

FT_12_4 = 6.0
FT_4_8 = 7.0
FT_8_12 = 3.0
FT_8_12AM = 4.0
PT_12_4 = 2.0
PT_4_8 = 3.0
PT_8_12 = 1.0
PT_8_12AM = 2.0
Total Cost = $ 2624.0
: 0.03
import numpy as np
from scipy.optimize import linear_sum_assignment

# Define the distance matrix


distance_matrix = np.array([
[np.inf, 13, 2, 15, 15, 15],
[13, np.inf, 14, 1, 12, 12],
[2, 14, np.inf, 16, 14, 14],
[15, 1, 16, np.inf, 10, 10],
[15, 12, 14, 10, np.inf, 4],
[15, 12, 14, 10, 4, np.inf]
])

def solve_tsp(distance_matrix):
# Apply the linear_sum_assignment to find the minimum cost in the assignment problem
row_ind, col_ind = linear_sum_assignment(distance_matrix)

# Initialize total cost and optimal route


total_cost = 0
optimal_route = [col_ind[0] + 1] # Add 1 for 1-based indexing

# Calculate the total cost of the optimal path


for i in range(len(col_ind) - 1):
total_cost += distance_matrix[col_ind[i], col_ind[i + 1]]
optimal_route.append(col_ind[i + 1] + 1) # Add 1 for 1-based indexing

# Add the cost of returning to the office from the last client
total_cost += distance_matrix[col_ind[-1], col_ind[0]]
optimal_route.append(optimal_route[0]) # Append the office at the end to return

return total_cost, optimal_route

total_cost, optimal_route = solve_tsp(distance_matrix)

print(f"The optimal route is: {optimal_route} with a total distance of: {total_cost}")
The optimal route is: [3, 4, 1, 2, 6, 5, 3] wi

nment problem
1, 2, 6, 5, 3] with a total distance of: 74.0
import networkx as nx

# Create a directed graph


G = nx.DiGraph()

# Add edges along with their capacities to the graph


G.add_edge('1', '2', capacity=40)
G.add_edge('1', '3', capacity=40)
G.add_edge('2', '4', capacity=10)
G.add_edge('2', '5', capacity=10)
G.add_edge('3', '4', capacity=15)
G.add_edge('3', '6', capacity=20)
G.add_edge('4', '5', capacity=20)
G.add_edge('4', '6', capacity=10)
G.add_edge('4', '7', capacity=10)
G.add_edge('5', '7', capacity=30)
G.add_edge('6', '7', capacity=20)

# Find the maximum flow from the source (node 1) to the sink (node 7)
flow_value, flow_dict = nx.maximum_flow(G, '1', '7')

# Print the maximum flow value


print("The maximum flow from node 1 to node 7 is:", flow_value)

# Print the flow on each edge


print("The flow through the network is as follows:")
for start_node, flow in flow_dict.items():
for end_node, value in flow.items():
print(f"Flow from node {start_node} to node {end_node}: {value}")
e sink (node 7)

node}: {value}")
The maximum flow from node 1 to node 7 is: 55
The flow through the network is as follows:
Flow from node 1 to node 2: 20
Flow from node 1 to node 3: 35
Flow from node 2 to node 4: 10
Flow from node 2 to node 5: 10
Flow from node 3 to node 4: 15
Flow from node 3 to node 6: 20
Flow from node 4 to node 5: 15
Flow from node 4 to node 6: 0
Flow from node 4 to node 7: 10
Flow from node 5 to node 7: 25
Flow from node 6 to node 7: 20
REGIONAL ANALYSIS

import seaborn as sns


import matplotlib.pyplot as plt

# Regional Analysis
plt.figure(figsize=(12, 6))

# Sales by Region
ax1 = plt.subplot(121)
sales_plot = sns.barplot(x='Region', y='Sales', data=data, estimator=sum, ax=ax1)
plt.title('Total Sales by Region')

# Adding data labels to Sales plot


for p in sales_plot.patches:
ax1.annotate(format(p.get_height(), '.2f'),
(p.get_x() + p.get_width() / 2., p.get_height()),
ha = 'center', va = 'center',
xytext = (0, 10),
textcoords = 'offset points')

# Profit by Region
ax2 = plt.subplot(122)
profit_plot = sns.barplot(x='Region', y='Profit', data=data, estimator=sum, ax=ax2)
plt.title('Total Profit by Region')

# Adding data labels to Profit plot


for p in profit_plot.patches:
ax2.annotate(format(p.get_height(), '.2f'),
(p.get_x() + p.get_width() / 2., p.get_height()),
ha = 'center', va = 'center',
xytext = (0, 10),
textcoords = 'offset points')

plt.tight_layout()
plt.show()
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from statsmodels.tsa.arima.model import ARIMA
import warnings

# Load dataset
file_path = "/Users/kaustubhrath/Downloads/Supermart Grocery Sales - Retail Analytics Dataset (2).csv" # Replace with the a
data = pd.read_csv(file_path)

# Parsing the 'Order Date' in the format "day, date month year"
data['Order Date'] = pd.to_datetime(data['Order Date'], format='%A, %d %B %Y')
data.set_index('Order Date', inplace=True)

# Resample data monthly and sum sales


monthly_sales = data['Sales'].resample('M').sum()

# Time Series Decomposition


decomposition = seasonal_decompose(monthly_sales, model='additive')
# Plotting Time Series Decomposition
plt.figure(figsize=(14, 7))
plt.subplot(411)
plt.plot(monthly_sales, label='Original')
plt.legend(loc='best')
plt.subplot(412)
plt.plot(decomposition.trend, label='Trend')
plt.legend(loc='best')
plt.subplot(413)
plt.plot(decomposition.seasonal, label='Seasonality')
plt.legend(loc='best')
plt.subplot(414)
plt.plot(decomposition.resid, label='Residuals')
plt.legend(loc='best')
plt.tight_layout()
plt.show()

# ARIMA Model for Forecasting


warnings.filterwarnings("ignore")
p, d, q = 1, 0, 1 # Initial estimates
arima_model = ARIMA(monthly_sales, order=(p, d, q))
arima_result = arima_model.fit()

# Forecasting
forecast_periods = 12
forecast_result = arima_result.get_forecast(steps=forecast_periods)
forecast_mean = forecast_result.predicted_mean
forecast_conf_int = forecast_result.conf_int()

# Plotting Forecast
plt.figure(figsize=(12, 6))
plt.plot(monthly_sales, label='Historical Monthly Sales')
plt.plot(forecast_mean, label='Forecasted Sales', color='red')
plt.fill_between(forecast_conf_int.index,
forecast_conf_int.iloc[:, 0],
forecast_conf_int.iloc[:, 1],
color='pink', alpha=0.3)
plt.title('Monthly Sales Forecast')
plt.xlabel('Date')
plt.ylabel('Sales')
plt.legend()
plt.show()
th the actual path

You might also like