Ask Your Question

Revision history [back]

Indeed var('a[0]') is not allowed, because it requires the name to be a valid Python identifier (probably because it wants to be able to inject it into the namespace). However we don't care about injecting into the namespace, because this is effectively already done through the name of the list.

Reading the source of var we find it calls SR.var which calls SR.symbol. This is the one we want:

sage: A = [SR.symbol('A[%d]' % j) for j in range(4)]
sage: A[3]^2
A[3]^2

Note that not all expressions are immediately valid C expressions in this way, e.g. you still have to transform a^b to pow(a, b) or something similar.

Indeed var('a[0]')var('A[0]') is not allowed, because it requires the name to be a valid Python identifier (probably because it wants to be able to inject it into the namespace). However we don't care about injecting into the namespace, because this is effectively already done through the name of the list.

Reading the source of var we find it calls SR.var which calls SR.symbol. This is the one we want:

sage: A = [SR.symbol('A[%d]' % j) for j in range(4)]
sage: A[3]^2
A[3]^2

Note that not all expressions are immediately valid C expressions C-expressions in this way, e.g. you still have to transform a^b to pow(a, b) or something similar.

Indeed var('A[0]') is not allowed, because it requires the name to be a valid Python identifier (probably because it wants to be able to inject it into the namespace). However we don't care about injecting into the namespace, because this is effectively already done through the name of the list.

Reading the source of var we find it calls SR.var which calls SR.symbol. This is the one we want:

sage: A = [SR.symbol('A[%d]' % j) for j in range(4)]
sage: A[3]^2
A[3]^2

Note that not all expressions are immediately valid C-expressions in this way, e.g. you still have to transform a^b to pow(a, b) or something similar.similar. For this purpose you can e.g. convert the expression to a sympy expression with sympy.sympify(...) and use their C-code generator.