Reputation: 301
I want to convert a Sage symoblic expression like:
y = 5*x + 7^x + 3*x^2
to a string which I can access by subscripting ( y[0] = '5', y[1] = '*', etc.
I need to do that because I want to calculate the number of occurrence of a specific variable in an expression. In above example the variable 'X' occures 3 times.
I would also appreciate if someone knew another way to achieve that.
Upvotes: 3
Views: 3881
Reputation: 352959
I think everyone's misreading the problem -- we're starting from a Sage symbolic expression.
sage: y = 5*x + 7^x + 3*x^2
sage: y
7^x + 3*x^2 + 5*x
sage: type(y)
<type 'sage.symbolic.expression.Expression'>
I would write a little recursive walker using operands()
and operator()
:
def var_counter(someexpr, v):
tor = someexpr.operator()
if tor is None:
return int(v in someexpr.variables())
else:
return sum(var_counter(operand, v) for operand in someexpr.operands())
which seems to work:
sage: x, x2, x3 = var("x x2 x3")
sage: y = 5*x + 7^x + 3*x^2 + x2**(x3+3*sin(x))
sage: var_counter(y, x)
4
sage: var_counter(y, x2)
1
sage: var_counter(y, x3)
1
And if you want to convert the expression to a string, simply call str
:
sage: str(y)
'7^x + 3*x^2 + 5*x + x2^(x3 + 3*sin(x))'
sage: str(y)[2]
'x'
sage: str(y)[6]
'3'
Upvotes: 4