Determine the depth of an array
K, 4 bytes
#,/\
In K, ,/
will join all the elements of a list. The common idiom ,//
iterates to a fixed point, flattening an arbitrarily nested list completely. ,/\
will iterate to a fixed point in a similar way, but gather a list of intermediate results. By counting how many intermediate results we visit before reaching the fixed point (#
), we get the answer we want: the maximum nesting depth.
"Count of join over fixed-point scan".
In action:
(#,/\)'(,1
1 2 3
,1 2 3
(3;(3;,3;3);3)
,((,1;2);(3;,4)))
1 1 2 3 4
Retina, 10
- Saved 1 byte thanks to @ӍѲꝆΛҐӍΛПҒЦꝆ
- Saved 14 extra bytes thanks to @MartinBüttner
+`\w|}{ {
Here the input format is a bit contrived - _
characters are used for list separators, so an input would look like this {1_{{2_3_{{4}_5}_6_{7_8}}_9_{10_{{{11}}}}_12_13}_14}
- Stage 1 - repeatedly remove
}{
and all other\w
characters. This has the effect of a) making all lists at all levels consist of only one element and b) removing all non-list-structural characters. - Stage 2 - count remaining
{
. This gives the deepest level of nesting.
Try it online.
If that's too much of a stretch, then the previous answer was:
Retina, 13
Assumes lists are contained in curly braces {}
.
+`[^}{]|}{ {
Try it online.
Python 2, 33 bytes
f=lambda l:l>{}and-~max(map(f,l))
Recursively defines the depth by saying the depth of a number is 0, and the depth of a list is one more than the maximum depth of its elements. Number vs list is checked by comparing to the empty dictionary {}
, which falls above numbers but below lists on Python 2's arbitrary ordering of built-in types.