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)
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!!
(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))