我正在尝试使用for循环为这个线性优化问题添加约束。限制是。。。x1A+x1B+x1C+x1D=1,x2A+x2B+x2C+x2D=1等…
Traceback错误发生在循环的第一次运行中,我很难弄清楚原因。如有任何帮助,我们将不胜感激!
problem2 = LpProblem("Problem_2",LpMinimize)
Letter=['A','B','C','D']
Number=['1','2','3','4']
NumArray = [185,225,193,207],[200,190,175,225],[330,320,315,300],[375,389,425,445]
NumArray=makeDict([Number,Letter], NumArray)
[problem2_vars = LpVariable.dicts("x",(Number, Letter),lowBound=0,cat='Binary')
problem2_vars['1']['A']
problem2 += lpSum([problem2_vars[i][j]*NumArray[i][j] for i in Number for j in Letter])
for j in Number:
problem2 += lpSum([problem2_vars[j,'A']]) == 1,"%s"%j][1]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-31-04a89d6c02e1> in <module>
2
3 for j in Number[0:]:
----> 4 problem2 += lpSum([problem2_vars[j,'A']]) == 1,"%s"%j
KeyError: ('1', 'A')
您在一小段代码中遇到了不少语法问题!:(
几点建议:
- 你为什么"逃逸";所有带反斜杠的东西
- 你不需要把你的变量放在一个列表里。。。不清楚你在那里用括号等做什么
- 错误的主要问题是没有向
LpVariable.dicts
传递要使用的索引列表。您只是传入了一个包含两个列表的元组
以后,试着像下面的例子一样打印你的模型,看看到底在构建什么。如果你在谷歌上搜索pulp
的例子(或者看看这个网站上有很多被标记的例子(,我认为你可以避免一些语法混乱。祝你好运
from pulp import *
p2 = LpProblem("p2", LpMinimize)
# data
ltrs = ['A', 'B']
nums = [1, 2]
coefs = { ('A', 1): 22,
('A', 2): 42,
('B', 1): 7,
('B', 2): 79}
x = LpVariable.dicts('x', indexs=coefs.keys(), cat='Binary')
# objective
p2 += lpSum(x[ltr, num] * coefs[ltr, num] for (ltr, num) in coefs.keys())
# constraint
for num in nums:
p2 += lpSum(x[ltr, num] for ltr in ltrs) == 1
sol = p2.solve()
print(p2)
print(sol)
收益率:
...
Result - Optimal solution found
Objective value: 49.00000000
Enumerated nodes: 0
Total iterations: 0
Time (CPU seconds): 0.00
Time (Wallclock seconds): 0.00
Option for printingOptions changed from normal to all
Total time (CPU seconds): 0.00 (Wallclock seconds): 0.00
p2:
MINIMIZE
22*x_('A',_1) + 42*x_('A',_2) + 7*x_('B',_1) + 79*x_('B',_2) + 0
SUBJECT TO
_C1: x_('A',_1) + x_('B',_1) = 1
_C2: x_('A',_2) + x_('B',_2) = 1
VARIABLES
0 <= x_('A',_1) <= 1 Integer
0 <= x_('A',_2) <= 1 Integer
0 <= x_('B',_1) <= 1 Integer
0 <= x_('B',_2) <= 1 Integer
1
[Finished in 242ms]