【问题标题】:how to optimize variables combination in a dictionary using Pulp python?如何使用 Pulp python 优化字典中的变量组合?
【发布时间】:2020-05-25 10:31:03
【问题描述】:

如果这是一个糟糕的问题,请原谅我。但是如何优化字典中的一组变量?

我发布了我的问题的 excel img。最大成本是 169,我必须选择 4/6 五成本才能获得最大利润?所以我的目标是结合 4/6(最大利润)和 169 美元的成本限制。

我能够学会从基本方程中获得最大值,但无法扩展以帮助解决我的示例。

 x1 = pulp.LpVariable("x1", 0, 40)   # 0<= x1 <= 40
 x2 = pulp.LpVariable("x2", 0, 1000) # 0<= x2 <= 1000

 prob = pulp.LpProblem("problem", pulp.LpMaximize)

 prob += 2*x1+x2 <= 100 
 prob += x1+x2 <= 80


 prob += 3*x1+2*x2

 status = prob.solve()
 pulp.LpStatus[status]

# print the results x1 = 20, x2 = 60
  pulp.value(x1)
  pulp.value(x2)    

来源:https://thomas-cokelaer.info/blog/2012/11/solving-a-linear-programming-problem-with-python-pulp/

【问题讨论】:

  • 我不明白这是什么意思:“选择 4/5 五成本”
  • 我只能从 5 个位置中选择 4 个。抱歉,应该更清楚。
  • 哪 5 个?我看到了 6 种可能性。
  • 非常抱歉。你是对的,它是 6。
  • 这是一个简单的优化模型。只需使用二进制变量x[i] 指示是否选择了项目i

标签: python optimization scipy linear-programming pulp


【解决方案1】:

这是“背包”问题的一个示例 - 您想挑选最有价值的物品,但要受限于可以选择的数量/成本。

以下内容:

from pulp import *

# PROBLEM DATA:
costs = [15, 25, 35, 40, 45, 55]
profits = [1.7, 2, 2.4, 3.2, 5.6, 6.2]
max_cost = 169
max_to_pick = 4

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

# VARIABLES
# x_i - whether to include item i (1), or not (0)
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)

返回:

Optimal
Profit = 17.0
Cost = 165.0
('x_0', '=', 0.0)
('x_1', '=', 1.0)
('x_2', '=', 0.0)
('x_3', '=', 1.0)
('x_4', '=', 1.0)
('x_5', '=', 1.0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 2016-07-02
    • 1970-01-01
    • 2015-08-17
    相关资源
    最近更新 更多