Strange behaviour of eval() with lambda functions inside a loop in python

冷暖自知 提交于 2020-05-15 09:55:26

问题


I have a string input file as below (one equation per line): 1.0 - x[0] - x[1] x[0] + x[1]

I am trying to convert these equations to lambda functions using eval() in python and then use them in an optimization scheme. Here is what I do:

def gen_const(input):
    list = input.read_eqs()
    for i in list:
        m = lambda x: eval(i)
        cons.extend([{'type': 'ineq', 'fun': m}])
    return cons

This cons fails when it is used inside the optimization scheme. However, if I only consider the first round inside the loop (i.e. first equation), the constraint works fine:

def gen_const(input):
    list = input.read_eqs
    for i in list[0:1]:
        m = lambda x: eval(i)
        cons.extend([{'type': 'ineq', 'fun': m}])
    return cons

Strangely enough, when I copy the exact same equations (literally copy from the input file, identical characters, spacing) it works fine too:

def gen_const(input):
    list = input.read_eqs
    m0 = '1.0 - x[0] - x[1]'
    m1 = 'x[0] + x[1]'
    cons.extend([{'type': 'ineq', 'fun': lambda x: eval(m0)}])
    cons.extend([{'type': 'ineq', 'fun': lambda x: eval(m1)}])
return cons

So I see this strange behaviour of eval() inside a loop and I really got stuck. I have read that eval is evil and searched through the alternatives but couldn't find a better way that works for my problem. I would really appreciate your help.

来源:https://stackoverflow.com/questions/50624105/strange-behaviour-of-eval-with-lambda-functions-inside-a-loop-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!