Pass formula as function parameter in python

I want to pass a formula inside a function parameter in Python, where the formula is a combination of other function parameters. In principle, it will look like this:

myfunction(x=2,y=2,z=1,formula="x+2*y/z") 6 

or more general:

 def myformula(x,y,z,formula): return formula(x,y,z) 

This will allow the user to select any arithmetic expression in terms of x, y, and z without creating a new function.

One of the possibilities that I foresee is to convert a string to a line of code inside a function. Is anything possible in Python? Or any other ideas? Thanks

+4
source share
4 answers

Using sympy , you can evaluate math expressions:

 import sympy as sy def myformula(formula, **kwargs): expr = sy.sympify(formula) return expr.evalf(subs=kwargs) print(myformula(x=2,y=2,z=1,formula="x+2*y/z")) # 6.00000000000000 print(myformula(x=2,y=2,z=1,formula="sin(x+yz)")) # 0.141120008059867 

But note that sympy.sympify uses eval , which makes it unsafe for arbitrary user input, since strings can be written to trick eval to execute arbitrary Python code .

A safer alternative is to create a parser to parse strictly restricted mathematical expressions. Here are some examples.

+9
source

Your "myFormula" is not much different from the usual lambda expression, except that the added baggage must parse the string into executable Python.

 (lambda x,y,z: x + 2*y/z)(5, 2, 10) 

So you can just define myFormula as

 def myFormula(*args, formula): formula(*args) 

and name him

 myFormula(5, 2, 10, lambda x, y, z: x + 2*y/z) 
+2
source

You can use eval , but you have to be careful. For this to work, the variables must match those within the scope of the function. Please note that if the user entered the formula "a+b/c" , it would be erroneous, because she does not know what to do with them, she knows only x , y and z .

 def myFormula(x,y,z, formula): return eval(formula) myFormula(5,10,2, "x+y/z") 

Result

 10 
0
source

You can try using the lambda function. Something like this might suit you:

 def myFormula(x,y,z): return lambda x,y,z: x+2*y/z 

Thus, you do not need to define a new function, and you do not need to pass anything extra as an argument.

Additional information on lambda functions: http://www.diveintopython.net/power_of_introspection/lambda_functions.html

http://pythonconquerstheuniverse.wordpress.com/2011/08/29/lambda_tutorial/

https://docs.python.org/2/reference/expressions.html#lambda

0
source

Source: https://habr.com/ru/post/1265900/


All Articles