我正在用Python编写可用于求解方程式的代码。用户必须首先通过raw_input()输入代码,然后将其用于使用eval()在循环中为每个x计算y,如下所示:
#some imports (math) and other irrelevant code
Code = raw_input('please enter your equation')
Low = raw_input('please enter the lowest number in the domain')
High = raw_input('please enter the highest number in the domain')
X = Low
While X <= High:
Y = eval(code)
#complicated code to solve equation
X += #number depending on the amount of decimals
#simpler code to print the result
问题在于,每个循环使用eval()解析输入代码非常慢。有没有办法只解析一次代码,然后在程序的其余部分中将其用作函数?
您可以使用预先编译表达式compiler.compile()
(自Python v2.6起已弃用)。
使用Python 3.x:
还要看看:Python:加快重复执行的eval语句的方法吗?
编辑
一些例子:
>>> expr = 'x*x + 2*x + 1'
>>> expr_obj = compile(expr, '', 'eval')
>>> x = 1
>>> y = eval(expr)
现在
>>> y
4
>>> x = 2
>>> y = eval(expr)
>>> y
9
compile
是eval
(和exec
)的较低版本。它不评估/执行您的表达式/语句,但返回可以执行此操作的代码对象。
PS作为eval
在用户提交的字符串上使用的一般规则,您必须非常小心接受的内容(这是一个潜在的安全漏洞)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句