Getting all leaves from an expression

I would like to get a List (ideally a set - drop repetition), but provided that there is no direct way to do this, I just use Union ) of the leaves from this expression.

For example, the expression

 ArcTan[(-1 + 2*x)/Sqrt[3]]/Sqrt[3] 

has a LeafCount 18:

  • -thirteen)
  • 2 (3)
  • 3 (2)
  • x
  • Arctan
  • Plus
  • Power (2)
  • Rational (2)
  • Time (3)

so I would like something like

 {-1, 2, 3, x, ArcTan, Plus, Power, Rational, Times} 

Actually, I really need functions, so

 {ArcTan, Plus, Power, Rational, Times} 

would be ideal - but presumably there’s not a very complicated way to filter them out when I get them.

I got lucky with

 H[s_] := If[LeafCount[s] == 1, s, Head[s]] H /@ Level[expr, 1, Heads -> True] H /@ Level[expr, 2, Heads -> True] (* ... *) 

but I feel that there must be a better way.

+6
source share
4 answers

Your own solution does not seem bad:

 expr = ArcTan[(-1 + 2*x)/Sqrt[3]]/Sqrt[3]; H[s_] := If[LeafCount[s] == 1, s, Head[s]] H /@ Level[exp, -1, Heads -> True] // Union 
  {-1, 2, 3, ArcTan, Plus, Power, Rational, Times, x} 

The Brett Champion method is more streamlined, but I would change it a bit:

 Union@Cases [expr, h_[___] :> h, {0, -1}] 

This way you raise the top-level head, for example ArcTan in:

 expr = ArcTan[(-1 + 2*x)/Sqrt[3]]; 
+7
source

You can use Cases for this:

 In[176]:= Cases[ArcTan[(-1 + 2*x)/Sqrt[3]]/Sqrt[3], h_[___] :> h, {0,Infinity}] // DeleteDuplicates Out[176]= {Rational, Power, Times, Plus, ArcTan} 
+8
source

In the original question, you can get all the leaves using a Level with the level spec {-1} and resolve with your heads.

 In[87]:= Level[ArcTan[(-1 + 2*x)/Sqrt[3]]/Sqrt[3], {-1}, Heads -> True] Out[87]= {Times, Power, 3, -(1/2), ArcTan, Times, Power, 3, -(1/ 2), Plus, -1, Times, 2, x} 

Daniel Lichtblau

+6
source

Here is what I came up with ...

 In[92]:= f[e_] := DeleteDuplicates[Prepend[Head[#] & /@ Level[e, Depth[e]], Head[e]]] In[93]:= f[ArcTan[(-1 + 2*x)/Sqrt[3]]/Sqrt[3]] Out[93]= {Times, Integer, Rational, Power, Symbol, Plus, ArcTan} 

Then you can easily remove Integer and Symbol .


Edit:

Now leave the expression in the list to make sure we get the top head. (The original expression had Times as the head, but it was also double inside.

 In[139]:= a = {ArcTan[(-1 + 2*x)/Sqrt[3]]/Sqrt[3]} In[140]:= TreeForm[a, AspectRatio -> .7] 

Treeform

 In[142]:= f[a] Out[142]= {List, Integer, Rational, Power, Symbol, Times, Plus, ArcTan} 
+4
source

Source: https://habr.com/ru/post/895364/


All Articles