Message Boards Message Boards

0
|
9767 Views
|
9 Replies
|
12 Total Likes
View groups...
Share
Share this post:

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

Posted 7 years ago

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
9 Replies

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

POSTED BY: Themis Matsoukas

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
Posted 7 years ago

It is a new method, wonderful!

POSTED BY: Math Logic
Posted 7 years ago

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

POSTED BY: Alexey Popkov

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
Posted 7 years 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
Posted 7 years 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
Posted 7 years ago

Oh?so simple,Thanks very much!!

POSTED BY: Math Logic

Try

Depth[a]    (*  Out:  4  *)
POSTED BY: Henrik Schachner
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract