python - 使用变量的向量语法使用 PULP 进行二进制整数编程?

标签 python pulp

Python 库 PULP 的新手,我发现该文档有点无用,因为它不包含使用变量列表的示例。我试图在下面创建一个绝对简约的示例来说明我的困惑。

import pulp
IDENTIFIERS = ['A','B','C','D','E']
PRICES      = dict( zip( IDENTIFIERS, [100.0, 99.0, 100.5, 101.5, 200.0 ] ) )
n           = len( IDENTIFIERS )

x     = pulp.LpVariable.dicts( "x", indexs = IDENTIFIERS, lowBound=0, upBound=1, cat='Integer', indexStart=[] )
prob  = pulp.LpProblem( "Minimalist example", pulp.LpMaximize )
prob += pulp.lpSum( [ x[i]*PRICES[i] for i in IDENTIFIERS ]  ), " Objective is sum of prices of selected items "
prob += pulp.lpSum( [ x[i] for i in IDENTIFIERS ] )==2, " Constraint is that we choose two items "
prob.solve()
for ident in IDENTIFIERS:
    if x[ident]==1:
        print ident + " is in the basket "

输出是:

A is in the basket 
B is in the basket 
C is in the basket 
D is in the basket 
E is in the basket

优化器没有识别我们只添加两个值的约束。

最佳答案

我会把它留在这里,以防其他人同样愚蠢,但实际上上面的例子工作正常。我只是没有正确检查结果。相反:

def printProb( prob ):
    for v in prob.variables():
       print v.name, "=", v.varValue
    print "Status:", pulp.LpStatus[ prob.status ]

表明解决方案是正确的。

关于python - 使用变量的向量语法使用 PULP 进行二进制整数编程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31410972/

相关文章:

python - SymPy:如何在 Google Colab 的一个单元格中输出多个 LaTex 方程?

python - 将列表拆分为N个列表,并在多线程中将每个列表分配给一个worker

python - 添加许多约束时 PuLP 非常慢

python - PULP:最小化一组向量的最大值

python - PuLP 输出到 numpy 数组

python - 根据条件在 Jupyter Notebook 中显示 DataFrame

python - 如何在 matplotlib x 轴上显示日期而不是序列号

python - Flask 应用程序不会像 wsgi 一样重新启动扭曲的 16.4.X

Python Pulp 线性规划约束

python - 我的 PuLP (使用线性编程的批量大小)代码中不断出现错误,出了什么问题?