TypeError: unsupported operand type(s) for +: 'generator' and 'generator'

点点圈 提交于 2019-12-22 12:23:03

问题


I have a problem with adding three expressions in my objective function. I used quicksum to build each expression. However, when I try to add them together I get an error that I cannot use +/- operands on class 'generator'.

Here is the last part of my code:

# the shipping cost expression
expr_sc = []
for j in J:
    for k in K:
        expr_sc.append(quicksum(r_jk[(j, k)]*x[(i, j, k)]) for i in I)

m.setObjective((quicksum(item_rev) for item_rev in expr_rev) -
               ((quicksum(item_pc) for item_pc in expr_pc) + (quicksum(item_sc) for item_sc in expr_sc)),
               GRB.MAXIMIZE)

Update:

here is the actual problem that I am trying to solve: Objective Function The problem is I don't know how to write this expression in Gurobi Python!!


回答1:


(quicksum(item_rev) for item_rev in expr_rev) evaluates to a generator expression.

If the one line for loop is inside the parenthesis - (...) - you get a generator object. Here's a small example to illustrate what I mean:

>>> (x for x in range(5)) # shorthand for creating generators
<generator object <genexpr> at 0xb74308ec>

See docs for more info.

It seems you're trying to pass individual items from given lists to quicksum, but instead you're creating generators, unintentionally.

To fix this error, directly pass the objects to quicksum:

m.setObjective(
    quicksum(expr_rev) - (quicksum(expr_pc) + quicksum(expr_sc)),
    GRB.MAXIMIZE
)

UPDATE:

There also seems to be a problem at

expr_sc.append(quicksum(r_jk[(j, k)]*x[(i, j, k)]) for i in I)

Change that line like this:

expr_sc.append(quicksum(r_jk[(j, k)] * x[(i, j, k)] for i in I))


来源:https://stackoverflow.com/questions/46476155/typeerror-unsupported-operand-types-for-generator-and-generator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!