Python 二元整数规划与纸浆使用向量语法的变量?

Python 二元整数规划与纸浆使用向量语法的变量?,python,pulp,Python,Pulp,python库的新手,我发现文档有些没有帮助,因为它没有包含使用变量列表的示例。我试图在下面创建一个绝对极简主义的例子来说明我的困惑 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

python库的新手,我发现文档有些没有帮助,因为它没有包含使用变量列表的示例。我试图在下面创建一个绝对极简主义的例子来说明我的困惑

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 ]

表明解决方案是正确的

你可以接受自己的答案,如果它解决了你的问题。这有助于其他人过滤未回答的问题。