Message Boards Message Boards

[✓] Know the number of braces in an expression?

GROUPS:

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?

POSTED BY: Math Logic
Answer
19 days ago

Try

Depth[a]    (*  Out:  4  *)
POSTED BY: Henrik Schachner
Answer
19 days ago

Oh,so simple,Thanks very much!!

POSTED BY: Math Logic
Answer
19 days ago

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:

2 Count[a, List, \[Infinity], Heads -> True]

two because for every list we have an opening and closing bracket.

POSTED BY: Sander Huisman
Answer
19 days ago

Actually the required answer is 3.

In[12]:= a = {1, 2, {3, 4, {5}}};
Count[a, List, \[Infinity], Heads -> True]

Out[13]= 3
POSTED BY: Syd Geraghty
Answer
16 days ago

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?

POSTED BY: Math Logic
Answer
15 days ago

The FullForm expression for a is

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
POSTED BY: Themis Matsoukas
Answer
15 days ago

It is a new method, wonderful!

POSTED BY: Math Logic
Answer
15 days ago

FullForm is redundant because Position already operates on FullForm by default.

POSTED BY: Alexey Popkov
Answer
14 days ago

Good point. On the other hand, it shows how the command actually works.

POSTED BY: Themis Matsoukas
Answer
13 days ago

Group Abstract Group Abstract