0

I've generated a variable names for pN from N=0 to n:

p0, p1, p2, p3, p4,....,pn

So far I got:

P = ['p0', 'p1', 'p2',..., 'pn']

What I want to do now is convert them into variable names to be called upon and used in a function. Convert 'p0' to p0, and so on for all of the values in

P = ['p0', 'p1', 'p2',..., 'pn'] 

So it becomes

P = [p0, p1, p2,..., pn]

Then generate functions using the variables:

Fi = P[i]/2

ie:

F0 = p0/2
F1 = p1/2
F2 = p2/2

Problem is I don't know how to convert 'pn' to pn properly, then generate functions based on pn. How do I do that? Or rather, what am I doing wrong?

Here's what I got:

# Define the constants
# ====================
k = 1
m = 1

# Generate the names
# ==================
n = 10 # Number of terms
P = [] # Array for momenta names
Q = [] # Array for positon names
for i in range (n): # Generate the names for
    p = "p"+str(i)  # momentum
    q = "q"+str(i)  # positon
    # Convert the names into variales
    exec("%s = %d" % p)
    exec("%s = %d" % q)
    # Put the names into the arrays
    P.append(p)
    Q.append(q)
# Print the names out for error checking
print(P)
print(Q)

# Generate the functions
# ======================
Q_dot = []

for i in range(n):
    def Q_dot(P[i]):
        q_dot = P[i] / m
        Q_dot.append(q_dot)
    i += 1

Note: I want to keep my variables as variables because I'm using the functions to solve a system of differential equations. My goal is to create a list of differential equations with the same format.

Kevin
  • 471
  • 1
  • 4
  • 10
  • 1
    You should look into dictionaries. Not only is your current approach difficult to build and maintain but you do yourself no favours having all these variables floating around. – roganjosh Mar 21 '18 at 19:57
  • 2
    Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – user3483203 Mar 21 '18 at 20:00
  • I did. The problem with that is that I have to assign a value to each of the variables, which I don't want to do because I'm using the variables to solve a differential equation. – Kevin Mar 21 '18 at 20:00
  • 2
    Use a *container* like a list or a dict, don't use a bunch of variables with dynamic execution using `exec`. That's a really bad design – juanpa.arrivillaga Mar 21 '18 at 20:00
  • I don't think the items I create in a list are variable, since the function I created don't recognize them as variables whet it is called upon. What should I do to have them be recognized as variables? – Kevin Mar 21 '18 at 20:14
  • YOU SHOULD put them into a dictionary as keys! – dgan Mar 21 '18 at 23:27

0 Answers0