简体   繁体   中英

How to run printed code Python

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

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}

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM