0

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
tcokyasar
  • 582
  • 1
  • 9
  • 26

2 Answers2

0

As pointed out in comments, dictionaries are the way to go. Stylistically, get in the habit of using return rather than printing results.

I've made some changes to your code, which should illustrate these points:

def test(mylist):
    d = {}
    for i in range(mylist):
        d['x'+str(i)] = i
    return d

test(3)  # {'x0': 0, 'x1': 1, 'x2': 2}
jpp
  • 159,742
  • 34
  • 281
  • 339
0

Trying to create dynamic variables is almost always a bad idea. It's dangers and often unnecessarily pollutes a namespace. However, I agree that just using plain variables here would be easier. Thus, you can return a list of values from test, and unpack them into three variables (x0, x1, and x2):

Create a list of your values:

def test(mylist):
    return [sy.symbols('x' + str(n), real=True) for n in range(mylist)]

And then create your gf list using the values in the list:

x0, x1, x2 = 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)]
Christian Dean
  • 22,138
  • 7
  • 54
  • 87
  • Thanks for your solution, but, writing: `x0, x1, x2 = test(3)` is what I want to avoid. I could also do the same. What if I have 100 variables? – tcokyasar Feb 10 '18 at 03:22
  • @user8028576 You _could_ use a list comprehension to create your `gf` list (`gf = [sy.diff(f, v) for v in test(3)]`), but I'm not sure how you'd evaluate your `f` equation? Is there a way it can be generalized? – Christian Dean Feb 10 '18 at 03:24
  • Arranging gf is the secondary task. If I could generalize xi= 'sy.symbols(xi, real=True). Then, it could be meaningful. – tcokyasar Feb 10 '18 at 04:13