0
0
SciPydata~30 mins

Bounds and constraints in SciPy - Mini Project: Build & Apply

Choose your learning style9 modes available
Bounds and Constraints in Optimization with SciPy
📖 Scenario: You are working as a data scientist helping a company optimize their product pricing to maximize profit. The prices must stay within certain limits, and some relationships between prices must hold true.
🎯 Goal: Build a Python program using SciPy to find the best prices for two products that maximize profit, while respecting given bounds and constraints.
📋 What You'll Learn
Create a function to calculate profit based on product prices
Set bounds for product prices
Add a constraint that one product price must be at least 1.5 times the other
Use SciPy's minimize function with bounds and constraints
Print the optimized product prices and maximum profit
💡 Why This Matters
🌍 Real World
Companies often need to find the best prices for products to maximize profit while respecting market or production limits.
💼 Career
Understanding how to apply bounds and constraints in optimization is key for data scientists working in pricing, operations, and resource allocation.
Progress0 / 4 steps
1
Create the profit function
Create a function called profit that takes a list prices with two elements: price of product A and price of product B. The function should return the total profit calculated as 5 * prices[0] + 3 * prices[1] minus the cost 2 * prices[0] + prices[1].
SciPy
Need a hint?

Use def profit(prices): to define the function and return the profit formula.

2
Set bounds for product prices
Create a variable called bounds that sets the price of product A between 1 and 10, and the price of product B between 2 and 8. Use a list of tuples for the bounds.
SciPy
Need a hint?

Use a list of tuples like [(1, 10), (2, 8)] to set bounds for each product price.

3
Add constraint and optimize
Create a dictionary called constraint with key type set to 'ineq' and key fun set to a lambda function that takes prices and returns prices[0] * 1.5 - prices[1]. Then, use scipy.optimize.minimize to minimize the negative profit function starting from initial prices [2, 3], with the bounds and constraints set to a list containing constraint. Store the result in result. Remember to import minimize from scipy.optimize. Negate the profit function by defining neg_profit = lambda prices: -profit(prices).
SciPy
Need a hint?

Use constraint = {'type': 'ineq', 'fun': lambda prices: prices[0] * 1.5 - prices[1]} and call minimize with neg_profit, initial guess, bounds, and constraints.

4
Print optimized prices and profit
Print the optimized prices from result.x with the message "Optimized prices:". Then print the maximum profit by calling profit with result.x and the message "Maximum profit:".
SciPy
Need a hint?

Use print("Optimized prices:", result.x) and print("Maximum profit:", profit(result.x)).