how to obtain leaf count (expression size) in sage?

83 views
Skip to first unread message

Nasser M. Abbasi

unread,
Aug 6, 2014, 10:53:30 AM8/6/14
to sage-s...@googlegroups.com
I searched for this but could not find it on google.

Is there a way in sage to determine the size of expression as given typically by leaf count? Similar to what is documented in Mathematica leafCount[] here

http://reference.wolfram.com/language/ref/LeafCount.html

"gives the total number of indivisible subexpressions in expr."

And also similar to Maple's

http://www.maplesoft.com/support/help/Maple/view.aspx?path=MmaTranslator/Mma/LeafCount&term=leafcount

I need a way to measure the size of resulting expression from sage to compare it with Mathematica's result and Maple's as well. I currently use leafCount() for this since both Maple and Mathematica have this function.

Does sage have similar function or another way to obtain this measure?

For example, given this expression

    (c + integrate(e^(2*x + sin(x)), x))*e^(-sin(x))

Then in Mathematica I would write

Clear[x, c];
expr = (c + Integrate[Exp[2*x + Sin[x]], x])*Exp[-Sin[x]];
LeafCount[expr]

              19

thanks
--Nasser

Emmanuel Charpentier

unread,
Aug 10, 2014, 9:09:26 AM8/10/14
to sage-s...@googlegroups.com
A first *very rough* approximation would be

def leaf_count(x):
    if x.operator()==None:
        return(1)
    return(sum(map(leaf_count, x.operands())))

but it's more comicated than that. compare :

sage: leaf_count(sin(a+b))
2


with :

sage: leaf_count(sin(a+b)/tan(a+b))
5


In other words : should function calls be counted or not ?

HTH,

--
Emmanuel Charpentier
Reply all
Reply to author
Forward
0 new messages