Ask Your Question
3

Human-readable form of operator() of an expression?

asked 3 years ago

greatpet gravatar image

updated 3 years ago

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?

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
5

answered 3 years ago

tmonteil gravatar image

updated 3 years ago

You 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
True
Preview: (hide)
link

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: 3 years ago

Seen: 387 times

Last updated: Mar 21 '21