在python中传递一个公式作为函数参数 [英] Pass a formula as a function parameter in python
问题描述
我想在Python中的函数参数中传递公式,其中公式是其他函数参数的组合。原则上,这看起来像这样:
myfunction(x = 2,y = 2,z = 1,formula =x + 2 * y / z)
6
或更常见:
def myformula(x,y,z,公式):
返回公式(x,y,z)
这将允许用户根据x,y和z选择任何算术表达式,而无需创建新函数。
我可以预见的一种可能性是在函数内的代码行中转换字符串。任何可能的东西在Python中可能?还是其他想法?
Thanks
导入sympy as sy
def myformula(formula,** kwargs):
expr = sy.sympify(公式)
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,公式=sin(x + yz)))
#0.141120008059867
但请注意 sympy.sympify
确实使用 eval
,这使得它适用于任意用户输入是不安全的。 b $ b因为可以将字符串组合成把戏 eval
执行任意Python代码。
一个更安全的方法是构建一个解析器来解析严格有限的数学表达式sions。
以下是一些例子
I want to pass a formula within a function parameter in Python where the formula is a combination of the other function parameters. In principle this would look like this:
myfunction(x=2,y=2,z=1,formula="x+2*y/z")
6
or more generaly:
def myformula(x,y,z,formula):
return formula(x,y,z)
This would allow the user to choose any arithmetic expression in terms of x, y, and z without having to create a new function.
One of the possibility I foresee is to convert the string in line of code within the function. Anything possible like that in Python? Or any other ideas? Thanks
Using sympy, you could evaluate mathematical 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+y-z)"))
# 0.141120008059867
But note that sympy.sympify
does use eval
which makes it unsafe to apply to arbitrary user input
since strings can be composed to trick eval
into executing arbitrary Python code.
A safer alternative is to build a parser to parse a strictly limited mathematical expressions. Here are a few examples
这篇关于在python中传递一个公式作为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!