i’m trying to solve an optimization problem by defining all the possible combinations of costs included in an array called values
, to solve the problem. To do this, i used the following method:
for i in range(len(values)):
for j in range(i+1, len(values)+1):
result.append(values[i:j])
The resulting array will have “len(values) + (len(values)-1) + (…) + 1” rows and if printed will be visualized as:
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
...
[1, 2, 3, 4, ..., len(values)]
...
[3]
[3, 4]
...
[3, 4, ..., len(values)]
etc...
I want to add a constraint to impose that the sum of the values contained in every group that I select from the array is lesser or equal than the thrshld
I have set. Previously I initialized a binary array x[]
with the same size of values
. After using m.optimize()
, the elements of x[]
will be true
if their index is the same as the last position in one of the combinations of values
i have chosen as part of the optimal solution, and false
otherwise…
To help me choose the right index of x[]
, I defined the following function:
def chooseindex(a, c, k):
for j in range(a):
c += a-j
if k <= c:
return j
in which a
will be the length of the original array, c
is the optional offset and k
is the index of the element of result
that is being considered
My solution was:
m.add_constr((sum(result[i])*(1 - x[len(result[i]) + chooseindex(len(values), 0, i) - 1]) for i in range(len(result)) <= (thrshld - 0.1))
The compiler returned the following error:
'<=' not supported between instances of 'generator' and 'float'
Afterwards I tried rearranging the terms as:
m.add_constr(sum(result[i])*(1 - x[len(result[i]) + chooseindex(len(values), 0, i) - 1])<= (thrshld - 0.1) for i in range(len(result))
but in return I got:
'generator' object has no attribute 'expr'
I also tried replacing thrshld
with a list, but with no luck. Any suggestions on how to make this work?
Walter Hampster White is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.