There are lots of constraints which I will use in optimization using scipy; so I need to generate the constraints by loop. Below there’s a sample of my constraints:
JavaScript
x
4
1
cons = ({'type': 'ineq', 'fun': lambda x: -x[0] - 2 * x[1] + 2},
2
{'type': 'ineq', 'fun': lambda x: -x[1] - 2 * x[1] + 2},
3
{'type': 'ineq', 'fun': lambda x: -x[2] - 2 * x[1] + 2})
4
There constraints are more than three… I use following loop to generate but I couldn’t get the same output.
JavaScript
1
5
1
cons ={}
2
for i in range(50):
3
cons['type'] = 'ineq'
4
cons['fun'] = lambda x: -x[i] - 2 * x[1] + 2
5
Advertisement
Answer
You are updating cons everytime. Try this
JavaScript
1
6
1
_tmp = []
2
for i in range(50):
3
_tmp.append({'type':'ineq', 'fun': lambda x: -x[i] - 2 * x[1] + 2})
4
5
cons = tuple(_tmp)
6
And this is more pythonic
JavaScript
1
2
1
cons = tuple([{'type':'ineq', 'fun': lambda x: -x[i] - 2 * x[1] + 2} for i in range(50)])
2