2

I would like to evaluate symbolic expression with np array

example:

import numpy as np
a = np.array([1]*4)
b = np.array([2]*4)
res = repr(a) + ' + ' + repr(b)
value = eval(res)

error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'array' is not defined

I have a workaround but I will know if I can solve my initial problem

workaround found on stackoverflow Python eval function with numpy arrays via string input with dictionaries

formula = 'x+y'
res = eval(formula,{'x':a, 'y':b})

Edit:

in order to solve the problem add the array definition in the import module

from numpy import array
parisjohn
  • 301
  • 2
  • 12

1 Answers1

2

Representations are of the form: array([1, 1, 1, 1]). So we need an array definition imported. So the following should work:

from numpy import array
a = array([1] * 4)
b = array([2] * 4)
res = repr(a) + ' + ' + repr(b)
eval(res)

Result:

array([3, 3, 3, 3])
JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57
  • thanks a lot for your prompt answer, it was the same kind of answer in this link : https://stackoverflow.com/questions/35750639/how-can-a-string-representation-of-a-numpy-array-be-converted-to-a-numpy-array/35750887 but I had not understood the problem with the array definition – parisjohn Oct 10 '17 at 08:58
  • `eval` is dangerous. I wonder if there's not a better way, e.g. with `sympy`. – Eric Duminil Oct 10 '17 at 18:50
  • I know sympy but I need the symbolic expression graph to make other more complicated stuff like Theano feature (GPU, OpenMP etc...), so I prefer to not use a whole module just to construct an expression tree – parisjohn Oct 11 '17 at 07:35