An expression may contains many braces, for example
a = {1, 2, {3, 4, {5}}}
How can I know how many braces are there in an expression by using a function?
Depth gives the maximum number of indices (+1) you can specify for an expression if you use it with Part. The number of braces are actually given by:
Depth
Part
2 Count[a, List, \[Infinity], Heads -> True]
two because for every list we have an opening and closing bracket.
Try
Depth[a] (* Out: 4 *)
The FullForm expression for a is
FullForm
a
List[1,2,List[3,4,List[5]]]
The number of opening or closing braces is equal to the number of lists in a:
Position[a // FullForm, List] // Length
Actually the required answer is 3.
In[12]:= a = {1, 2, {3, 4, {5}}}; Count[a, List, \[Infinity], Heads -> True] Out[13]= 3
Good point. On the other hand, it shows how the command actually works.
FullForm is redundant because Position already operates on FullForm by default.
Thank you ! But I am not familiar with [Infinity], Heads -> True. Is it the instance of levelspec in Count[expr,pattern,levelspec]? Could you please explain the meanings [Infinity], Heads -> True? How can they serve as the levelspec?
Oh?so simple,Thanks very much!!