1

I am using the scipy.optimize.minimize(...) routine and I need to specify the constraints argument which takes the form:

N = 50
cons = ({'type': 'ineq', 'fun': lambda x: x[0]<x[1]},
               {'type': 'ineq', 'fun': lambda x: x[1]<x[2]},
               {'type': 'ineq', 'fun': lambda x: x[2]<x[3]}, 
               ...)

which contains $N$ tuples of the form {'type': 'ineq', 'fun': lambda x: x[i]

I would like to create such dictionary using a loop (or other way) in the spirit of

cons = dict([{'type':'ineq','fun':lambda x[i]<x[i+1]} for i in range(0,N)])

I tried:

cons = zip(['fun' for i in range(0,N)], [lambda x: x[i]<x[i+1] for i in range(0,N)])

but it doesn't work and I don't know how to manage several keys and values.

1 Answers1

1

This problem is hard because of how python does their late binding closures... See this answer. In essence you need to do this:

N = 50
cons = tuple({'type':'ineq','fun':(lambda x, i=i: x[i] < x[i + 1])} for i in range(N))
print(cons[0]['fun']((1, 2, 3)))