-1

I need to use multiple constraints in scipy for optimization:

    cons = ({'type': 'eq', 'fun': cons0},\
         {'type': 'eq', 'fun': cons1},{'type': 'eq', 'fun': cons2}, ....)

I try to generate it by loop but cons0 or cons1 or cons3 is considered as a string and I get errors.

cons= []

for i in range(3):
     name = cons + str(i)   
     cons.append({'type': 'eq', 'fun': name})
SuperKogito
  • 2,998
  • 3
  • 16
  • 37
Berk
  • 263
  • 1
  • 14

1 Answers1

0

You can bypass this by using eval python function. In this specific case it will do exactly what you want. If you have a string and you want to access function that has this name just write eval, f.ex eval("cons0"). See the example

def fun0():
    print "Hey!"

def fun1():
    print "there"

funs = {}

for i in range(0,2):
    funs[i] = eval("fun%d" % i)

print funs

funs[0]()
funs[1]()

this prints:

{0: <function fun0 at 0x7f40ce1ab5f0>, 1: <function fun1 at 0x7f40ce1ab668>}
Hey!
there