How to use a string in a symbolic expression with SageMath?

269 Views Asked by At

I would like to use a string as part of a symbolic expression. For instance:

function('P')
var('x1 x2 x3 y1 y2 y3')
st = eval('y1,0,1')
sum(P(x1,y1,y2,y3),st)

How could I use st which is a string in the symbolic expression sum?

I want the same result as if I had typed directly:

sum(P(x1,y1,y2,y3),y1,0,1)
1

There are 1 best solutions below

0
On

Define a symbolic function P and some symbolic variables:

sage: P = function('P')
sage: x1, x2, x3, y1, y2, y3 = SR.var('x1, x2, x3, y1, y2, y3')

Define a triple (using a string and the eval function)

sage: st = eval('y1, 0, 1')
sage: st
(y1, 0, 1)

The question of how to attain the same result as

sage: sum(P(x1, y1, y2, y3), y1, 0, 1)
P(x1, 1, y2, y3) + P(x1, 0, y2, y3)

by using st is not really about how to use a string, since st is now a triple.

The required operation is called unpacking a tuple.

In Python, unpacking any iterable is achieved using *:

sage: sum(P(x1, y1, y2, y3), *st)
P(x1, 1, y2, y3) + P(x1, 0, y2, y3)