python中的双和表达式



我正在尝试使用Python中的Pulp解决优化问题,但我在表达约束时遇到了一些麻烦。

def Kakuro(M):
prob = pulp.LpProblem() 
rows = range(1,4)
cols = range(1,4)
vals = range(1,10)
X = pulp.LpVariable.dicts("X",(rows,cols,vals),cat='Binary')
for i in rows:
for j in cols:
prob += sum([X[i][j][k] for k in vals]) == 1

for i in rows:
for k in vals:
prob += sum([X[i][j][k] for j in cols]) == M[i][0] #This is expressing x_111+x_121+x_131=M[i]; x_112+x_122+x_132=M[i]...
for j in cols:
for k in vals:
prob += sum([X[i][j][k] for i in rows]) == M[0][j]
prob.solve() #prob.solve(pulp.PULP_CBC_CMD(msg=0))
solution = np.zeros((4,4))
for i in rows:
solution[i][0] = M[i][0]
for j in cols:
solution[0][j]=M[0][j]
for i in rows:
for j in cols:
for k in vals:
if X[i][j][k].value() == 1:
solution[i,j] = k

return solution

对于第二个和第三个For循环,我想说的是像等式一样x_{111}+x_{121}+x_{131}+x_{112}+ ... +x_{119}+x_{129}+x_{139}=M[i][0],但现在是x_111+x_121+x_131=M[i][0]。我怎么能在probb方程里有两个循环呢?

如果我明白你想做什么,你可以只是增加求和表达式,包括2个变量…比如:

for i in cols:
prob += sum(x[i][j][k] for j in rows for k in vals) <= M[i][0]

相关内容

  • 没有找到相关文章

最新更新