I am trying to create a function that runs printed code. For example,
def test(mylist):
mydict = {}
for i in range(mylist):
mydict[i] = ('x'+'%s' %i)
print ("%s = %s" %(mydict[i], i))
test(3)
Output:
x0 = 0
x1 = 1
x2 = 2
I basically want my function to run these printed commands and set x0=0
, x1=1
, and so on. I could not think of a way to do it. Thanks!
Edit:
I edited the code based on your dictionary idea. But, it does not still seem to be helping to solve for the gradient of a given function. Can you please help me on this?
import sympy as sy
def test(mylist):
d = {}
for i in range(mylist):
d['x'+str(i)] = 'sy.symbols(x%s, real=True)' %i
return d
test(3)
f = (1/3*x0**6 - 2.1*x0**4 + 4*x0**2 +
x0*x1 - 4*x1**2 + 4*x1**4 + x2)
gf = [sy.diff(f, x0), sy.diff(f, x1), sy.diff(f, x2)]
gf