You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

使用Python实现混合整数规划(MIP)求解指定约束的最大化问题

Solving the Mixed Integer Programming Problem in Python

First, let's align on the core problem requirements to make sure we're targeting the right solution:

  • We need to select exactly one row per unique X value
  • The sum of Y values from the selected rows must be ≤23
  • Our goal is to maximize the sum of Z values from the selected rows

For this task, the pulp library is a perfect fit in Python—it’s intuitive for setting up integer programming problems and matches the functionality of R’s lpSolve. If you don’t have it installed yet, run pip install pulp to get started.

Here’s a step-by-step implementation with explanations:

import pulp
import pandas as pd

# Step 1: Load the sample data
data = pd.DataFrame({
    'X': [1, 1, 1, 2, 2, 2, 3, 3, 3],
    'Y': [9, 7, 5, 9, 7, 5, 9, 7, 5],
    'Z': [25, 20, 5, 20, 10, 5, 10, 5, 5]
})

# Step 2: Initialize a maximization problem
prob = pulp.LpProblem("Maximize_Total_Z", pulp.LpMaximize)

# Step 3: Create binary variables for each row (1 = selected, 0 = not selected)
row_selection = pulp.LpVariable.dicts("Row", data.index, cat='Binary')

# Step 4: Define the objective function (maximize sum of Z for selected rows)
prob += pulp.lpSum([data.loc[i, 'Z'] * row_selection[i] for i in data.index])

# Step 5: Add constraints
# Constraint 1: Exactly one row per unique X group
for x_group in data['X'].unique():
    group_rows = data[data['X'] == x_group].index
    prob += pulp.lpSum([row_selection[i] for i in group_rows]) == 1, f"Single_Row_For_X_{x_group}"

# Constraint 2: Total Y of selected rows can't exceed 23
prob += pulp.lpSum([data.loc[i, 'Y'] * row_selection[i] for i in data.index]) <= 23, "Total_Y_Limit"

# Step 6: Solve the problem
prob.solve()

# Step 7: Extract and display results
print("Solution Status:", pulp.LpStatus[prob.status])
selected_rows = data.loc[[i for i in data.index if pulp.value(row_selection[i]) == 1]]
print("\nSelected Rows:")
print(selected_rows)
print(f"\nTotal Z Sum: {pulp.value(prob.objective)}")
print(f"Total Y Sum: {selected_rows['Y'].sum()}")

Expected Output

When you run this code, you’ll get exactly the desired result:

Solution Status: Optimal

Selected Rows:
   X  Y   Z
0  1  9  25
3  2  9  20
8  3  5   5

Total Z Sum: 50.0
Total Y Sum: 23

How This Works

  • Binary variables track which rows are chosen
  • The "one row per X" constraint ensures we pick exactly one option from each group
  • The Y sum constraint keeps us within the 23 limit
  • The objective function prioritizes maximizing total Z, which leads to selecting the highest Z values where possible (like X=1's 25 and X=2's 20) and then choosing the lowest Y option for X=3 to stay under the limit.

This implementation mirrors your R lpSolve solution—both solve the same mixed integer linear programming problem.

内容的提问来源于stack exchange,提问作者blehblehbleh

火山引擎 最新活动