First time here? Check out the FAQ!

Ask Your Question
0

Symbolic variables in loops

asked 10 years ago

Torero gravatar image

Hi, I got a list of symbolic variables defined like this: P = list(var('P_%d' % i) for i in range(2*n + 1))

But when I try to manipulate these Variables in a for-loop like: for k in range(2,n + 2,2): print(P_k)

I'll get an error "NameError: name 'P_k' is not defined" I'm guessing there is no k in P_k because its one entity 'P_k' :-D But I hope it's possible to fix this by using "%" like in the definition above. Anyone knows how to?

Thanks

Preview: (hide)

Comments

Also, probably n = something earlier in your code...

kcrisman gravatar imagekcrisman ( 10 years ago )

yeah. n = anything natural >= 2

Torero gravatar imageTorero ( 10 years ago )

3 Answers

Sort by » oldest newest most voted
1

answered 10 years ago

niles gravatar image

Does P[k] work?

Preview: (hide)
link
0

answered 10 years ago

kcrisman gravatar image

updated 10 years ago

for k in range(2,n + 2,2):
    print(eval("P_%s"%k))

Ugly, I admit. It's hard to just stick in these things. Niles' solution is better.

Edit: But if you insist (I note you also used print in your original example, so it was hard to anticipate your next issue)...

sage: n = 5
sage: P = list(var('P_%d' % i) for i in range(2*n + 1))
sage: for k in range(2,n + 2,2):
....:     tem = eval('P_%s' %k)
....:     x.subs(x=tem)
....:     
P_2
P_4
P_6
Preview: (hide)
link

Comments

I'm sorry. I hoped there is a direct way to get the variables and used print as a basic example. But this one is interesting. Unfortunately it substitutes x by P_k and not the other way around

Torero gravatar imageTorero ( 10 years ago )
0

answered 10 years ago

Torero gravatar image

@niles: P[k] works, but I need P_k in my loop. In fact I'm trying to substitute P_k by P[k]

@kcrisman: print(eval...) works fine, but N[k] = N[k].subs(eval('P_%s' %k = P[k])) doesn't (SyntaxError: keyword can't be an expression). But this is what I was aiming at.

One solution would be to redefine N[k] everytime any P_k changes. But that would kill my calculation period for bigger n, so that is my last resort

Preview: (hide)
link

Comments

Couldn't you just make, inside your loop, `temp = eval('P_%s' %k)` and use that in your loop? I'll edit my answer.

kcrisman gravatar imagekcrisman ( 10 years ago )

I don't understand. Why not just include the line "P_k = P[k]"?

niles gravatar imageniles ( 10 years ago )

1. P_k = P[k] doesn't work in loops with index k (because even if k = 2, P_k =! P_2) 2. When I got an equation using P_2 it will still have P_2 in it afterwards

Torero gravatar imageTorero ( 10 years ago )

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 10 years ago

Seen: 2,127 times

Last updated: Aug 14 '14