0

I have a string of formula lets said:

str1='(0.5-0.70*x0[0])**2+(0.5-0.70*x0[1])**2'

how can I pass it into lambda function fn Automatically by variable str1

fn= lambda x0: str1


The goal for this is I would like to get a function object:<function main.(x0)> and finally pass it to scipy.optimize.minimize(fn=fn), if you can solve this directly, you can skip the question above

Savir
  • 17,568
  • 15
  • 82
  • 136

1 Answers1

2

You could use eval():

from scipy.optimize import minimize
import numpy as np

str1='(0.5-0.70*x0[0])**2+(0.5-0.70*x0[1])**2'

x0 = np.ones(2)

minimize(lambda x0: eval(str1), x0=x0)
joni
  • 6,840
  • 2
  • 13
  • 20
  • This is a good answer, but the OP should keep in mind the warnings in [Why is using 'eval' a bad practice?](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice) – Steven Rumbalski Oct 26 '22 at 18:55