首页 > 解决方案 > 纸浆在选项/类型不能相同的地方添加新约束?

问题描述

下面的代码允许我根据预算(max_cost)和允许的选择(max_to_pick)优化利润。如何在无法选择同一个城市的情况下添加新约束。

from pulp import *

  # PROBLEM DATA:
  costs = [15, 25, 35, 40, 45, 55]
  profits = [1.7, 2, 2.4, 3.2, 5.6, 6.2]
  # city = ["NYC","SF","LA","SF","NYC","LA"]   NEW CONSTRAINTS
  max_cost = 200
  max_to_pick = 4

  # DECLARE PROBLEM OBJECT:
  prob = LpProblem("Mixed Problem", LpMaximize)

  # VARIABLES
  n = len(costs)
  N = range(n)
  x = LpVariable.dicts('x', N, cat="Binary")

  # OBJECTIVE
  prob += lpSum([profits[i]*x[i] for i in N])

  # CONSTRAINTS
  prob += lpSum([x[i] for i in N]) <= max_to_pick        # Limit number to include
  prob += lpSum([x[i]*costs[i] for i in N]) <= max_cost  # Limit max. cost

  # SOLVE & PRINT RESULTS
  prob.solve()
  print(LpStatus[prob.status])
  print('Profit = ' + str(value(prob.objective)))
  print('Cost = ' + str(sum([x[i].varValue*costs[i] for i in N])))

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

非常感谢!

标签: pythonpandasoptimizationmathematical-optimizationpulp

解决方案


假设您想限制选择以使列表city中的城市最多包含一次,那么添加如下约束应该可以做到这一点。它设置了一个约束,使得x分配给每个城市的决策变量之和最多为 1。

可能有一种更 Pythonic 的方式来创建列表索引。您可以按如下方式在一个衬里中创建所有这些,但我发现它更难遵循:

list_of_lists_of_indices = [[i for i in N if city[i] == c] for c in set(city)]

from pulp import *
# PROBLEM DATA:
costs = [15, 25, 35, 40, 45, 55]
profits = [1.7, 2, 2.4, 3.2, 5.6, 6.2]
city = ["NYC","SF","LA","SF","NYC","LA"] # NEW CONSTRAINTS

max_cost = 200
max_to_pick = 4
# DECLARE PROBLEM OBJECT:
prob = LpProblem("Mixed Problem", LpMaximize)
# VARIABLES
n = len(costs)
N = range(n)
x = LpVariable.dicts('x', N, cat="Binary")
# OBJECTIVE
prob += lpSum([profits[i]*x[i] for i in N])
# CONSTRAINTS
prob += lpSum([x[i] for i in N]) <= max_to_pick        # Limit number to include
prob += lpSum([x[i]*costs[i] for i in N]) <= max_cost  # Limit max. cost

# NEW CONSTRAINT
for c in set(city):
  index_list = [i for i in N if city[i] == c]
  prob += lpSum([x[i] for i in index_list]) <= 1

# SOLVE & PRINT RESULTS
prob.solve()
print(LpStatus[prob.status])
print('Profit = ' + str(value(prob.objective)))
print('Cost = ' + str(sum([x[i].varValue*costs[i] for i in N])))

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

推荐阅读