Skip to main content

expression manipulation - Count number of summands?


Consider


fun = a+b+c+d/e

If we want to get the number of summands, we can use Length[fun], which properly gives 5 in this case. However, if fun contains only a single term


fun = d/e

Then applying Length[fun] gives 2 since now it actually counts the number of terms in the multiplication instead of summation.



Therefore, Length is rather a hack than an actually reliable function to get the number of summands. Is there an efficient function that returns the number of summands reliably?



Answer



Best thing I can come up with is


cntSummands[expr_]:=If[Head[expr]===Plus,Length[expr],If[expr === 0, 0, 1]]

but this sounds like a terrible workaround. I am sure there are better ways?


Comments