FunctionRacerProblemsRace

Count the Boxes

BeginnerRecursionPython, JavaScript, TypeScript

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

items [1,[2,[3]],[4]]
returns 4

The outer list is one box, [2, [3]] is another, [3] is inside it, and [4] is the fourth.

Example 2

items [1,2,3]
returns 1

Only the outer list is a box; the integers inside it are not.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Recursion problems