Python 纸浆约束

Python pulp constraint

我正在尝试使用 pulp 库为 python 中的线性规划问题添加约束。我尝试了下面的代码。

for week in range(14,52), i in I.index:
    k = week
    model += sum(x[(i, j, week, B)] for week in range(k, k+13), 
                                        j in J.index) <= 1

其中 I 和 J 具有以下索引

I.index = ['A','B','C']
J.index = [1,2,3]

我得到的错误是 SyntaxError: Generator expression must be parenthesized if not sole argument。我研究过这个 link Generator expression must be parenthesized if not sole argument 但是它似乎并没有解决我的问题。感谢任何帮助。

或者 Duan 的评论看起来正确使用的语法应该是

for week in range(14,52), i in I.index:
    k = week
    model += sum(x[(i, j, week, B)] for week in range(k, k+13)
                                    for j in J.index) <= 1

但在这种情况下,如果您使用 lpSum() 函数,速度会快得多

for week in range(14,52), i in I.index:
    k = week
    model += lpSum(x[(i, j, week, B)] for week in range(k, k+13)
                                    for j in J.index) <= 1