编程语言
首页 > 编程语言> > 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 ]

表明解决方案是正确的.

标签:pulp,python
来源: https://codeday.me/bug/20191120/2040687.html