ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Sun, 21 Mar 2021 00:20:06 +0100Human-readable form of operator() of an expression?https://ask.sagemath.org/question/56286/human-readable-form-of-operator-of-an-expression/Consider the code below
sage: x,y=var('x y')
sage: (x+y).operator()
<function add_vararg at 0x7f9d56dbd430>
The output in the last line is a bit lengthy, and makes it hard for me to automatically test what kind of expression I have (e.g. determining if the expression is a sum or a product of operands). I would like to write code like this
if someExpression.operator() == plus:
print("this is a sum")
elif someExpression.operator() == multiply:
print("this is a product")
else:
print("this is something else")
How should I modify the if-else statement above to make it actually work?Sat, 20 Mar 2021 21:56:47 +0100https://ask.sagemath.org/question/56286/human-readable-form-of-operator-of-an-expression/Answer by tmonteil for <p>Consider the code below</p>
<pre><code>sage: x,y=var('x y')
sage: (x+y).operator()
<function add_vararg at 0x7f9d56dbd430>
</code></pre>
<p>The output in the last line is a bit lengthy, and makes it hard for me to automatically test what kind of expression I have (e.g. determining if the expression is a sum or a product of operands). I would like to write code like this</p>
<pre><code>if someExpression.operator() == plus:
print("this is a sum")
elif someExpression.operator() == multiply:
print("this is a product")
else:
print("this is something else")
</code></pre>
<p>How should I modify the if-else statement above to make it actually work?</p>
https://ask.sagemath.org/question/56286/human-readable-form-of-operator-of-an-expression/?answer=56290#post-id-56290You can define the `plus` and `multiply` operators as follows :
sage: from sage.symbolic.operators import add_vararg as plus
sage: from sage.symbolic.operators import mul_vararg as multiply
Then,
sage: (x+y).operator() == plus
True
sage: (x*y).operator() == multiply
True
Note that the operators are not duplicated, but are the same in memory:
sage: (x+y).operator()
<function add_vararg at 0x7fcf50e86e18>
sage: plus
<function add_vararg at 0x7fcf50e86e18>
sage: (x+y).operator() is plus
TrueSun, 21 Mar 2021 00:20:06 +0100https://ask.sagemath.org/question/56286/human-readable-form-of-operator-of-an-expression/?answer=56290#post-id-56290