Count the Boxes
Think of items as a box: a list that holds integers and, possibly, smaller boxes, which are lists of the same kind, nested to any depth. Return how many boxes there are in total, counting items itself and every list inside it at any level. An empty list is still a box, so [] gives 1 and [[], []] gives 3. Integers are not boxes.
A loop with a stack works, but the natural way is a function that counts one box and asks itself about each box inside it.
For example, [1, [2, [3]], [4]] gives 4: the outer box, [2, [3]], [3] and [4].
Example 1
The outer list is one box, [2, [3]] is another, [3] is inside it, and [4] is the fourth.
Example 2
Only the outer list is a box; the integers inside it are not.
Constraints
itemsholds at most 100 integers and at most 50 lists in total, countingitemsitself- Lists are nested at most 10 levels deep
-100 <= value <= 100for every integer
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Recursion problems
- Digit TallyBeginner
- Equal NeighboursBeginner
- Halving TotalBeginner
- Largest DigitBeginner
- Multiply It OutBeginner
- Nested SumBeginner
- Rising DigitsBeginner
- Ruler PatternBeginner