Ask Your Question
3

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

asked 2021-03-20 21:56:47 +0100

greatpet gravatar image

updated 2021-03-20 21:57:41 +0100

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?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
5

answered 2021-03-21 00:20:06 +0100

tmonteil gravatar image

updated 2021-03-21 12:01:16 +0100

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
edit flag offensive delete link more

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: 2021-03-20 21:56:47 +0100

Seen: 355 times

Last updated: Mar 21 '21