There is a line containing a mathematical expression of the form:
1/3+2/3 Is there a module that computes the value of such expressions?
There is a line containing a mathematical expression of the form:
1/3+2/3 Is there a module that computes the value of such expressions?
You can use eval
eval('1/3+2/3') here you can read https://docs.python.org/3/library/functions.html#eval
But usually with such functions there are security problems in case you get a string from outside (user input for example)
From a security point of view (as @Batanichek already said - with eval() you need to be very careful), performance and flexibility are better to use numexpr :
In [6]: import numexpr as ne In [7]: ne.evaluate('1/3+2/3') Out[7]: array(1.0) In [8]: var1=10 In [9]: var2=2 In [10]: ne.evaluate('var1**var2') Out[10]: array(100, dtype=int32) It is, by the way, faster for more complex calculations, supports the use of variables, supports NumPy, SciPy, etc.
Numexpr supports multi-threaded computing (using all available processor cores) and VML ΠΎΡ Intel (Vector Math Library, ΠΊΠΎΡΠΎΡΡΠΉ ΠΈΠ½ΡΠ΅Π³ΡΠΈΡΠΎΠ²Π°Π½ Π² ΠΈΠ½ΡΠ΅Π»ΠΎΠ²ΡΠΊΠΈΠΉ ΠΆΠ΅ Math Kernel Library (MKL)) .
An example of working with a regular ("Vanilla Python") array:
In [45]: lst = [1, 2.718281828] In [46]: ne.evaluate('log(lst)') Out[46]: array([ 0., 1.]) with a numpy array:
In [50]: a = np.array([1, 2.718281828]) In [51]: ne.evaluate('log(a)') Out[51]: array([ 0., 1.]) Performance comparison with NumPy for an array consisting of 1 million elements of type numpy.float64 :
In [36]: a = np.random.rand(10**6) In [37]: a.shape Out[37]: (1000000,) In [38]: len(a) Out[38]: 1000000 In [39]: %timeit np.log(a) 10 loops, best of 3: 24.3 ms per loop In [40]: %timeit ne.evaluate('log(a)') 100 loops, best of 3: 5.45 ms per loop In [41]: %timeit np.sqrt(np.sin(a)**2 + np.cos(a)**2) 10 loops, best of 3: 84.5 ms per loop In [42]: %timeit ne.evaluate('sqrt(sin(a)**2 + cos(a)**2)') 100 loops, best of 3: 6.32 ms per loop It seems like it is considered a safe analogue of eval
import ast try: print(ast.literal_eval(1/3+2/3)) except ValueError as err: print(err) Only here with this expression gives an error
ast.literal_eval('1*1') throws an exception. - Alex TitovSource: https://ru.stackoverflow.com/questions/606270/
All Articles