且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不使用exec的情况下生成PuLP变量和约束?

更新时间:2023-02-04 10:39:59

关键是要认识到可以拥有一个对象(可以在列表或字典中说一个),而不必明确绑定到对象名称.您可以创建一个对象,将其附加到列表中,并且只能将其引用为 some_list [2] .一旦您拥有了这种***,您的代码就会变得更加简单.

The key is recognizing that it's okay to have an object -- say one in a list or a dictionary -- which you don't have explicitly bound to a name. You can make an object, append it to a list, and only ever refer to it as some_list[2]. Once you allow yourself that freedom, your code can become much simpler.

在这里,我对输入进行了硬编码,因为这无关紧要:

Here I've hardcoded the inputs, because that doesn't matter:

from pulp import *

objs = [2,3,2,5,3]
weights = [1,2,2,1,3]
knapweight = 5

prob = LpProblem('Knapsack', LpMaximize)
xs = [LpVariable("x{}".format(i+1), cat="Binary") for i in range(len(objs))]

# add objective
total_prof = sum(x * obj for x,obj in zip(xs, objs))
prob += total_prof

# add constraint
total_weight = sum(x * w for x,w in zip(xs, weights))
prob += total_weight <= knapweight

status = prob.solve()
print(LpStatus[status])
print("Objective value:", value(prob.objective))
print ('\nThe values of the variables : \n')
for v in prob.variables():
    print(v.name, "=", v.varValue)

这给了我

Optimal
Objective value: 10.0

The values of the variables : 

x1 = 1.0
x2 = 1.0
x3 = 0.0
x4 = 1.0
x5 = 0.0

在这里,我正在列表理解中构建LpVariables

Here I'm building the LpVariables in the list comprehension

xs = [LpVariable("x{}".format(i+1), cat="Binary") for i in range(len(objs))]

然后将对象放在列表 xs 中.

where the objects then just live in the list xs.

>>> xs
[x1, x2, x3, x4, x5]
>>> xs[3]
x4
>>> type(xs[3])
<class 'pulp.pulp.LpVariable'>