Exercise 2: Summing a list of lists of lists of lists of lists of ...

Previous part

In the Advent of Code problem, we need to write code that finds the sum of sizes of a directory which can contain files and directories, each of which can contain files and directories, each of which can contain files and directories, each of which can contain files and directories, each of which can contain files and directories...

Let's explore a closely related but simpler problem: finding the sum of numbers in a list that may contain numbers or lists that may contain lists or numbers—you get the idea!

Exercise: Try to write a function that finds the sum of numbers in the following list.

[
 27,
 38,
 22,
 [42,
  [[18,
    47,
    [13,
     49,
     [26, 16, [[43, [8, 16, 35, 31, 46], 12], 19], 14, [[27], 36, 40, 44]]]]],
  [23, [38, 26, 5, 14], 25, 8, 12],
  24,
  39]]

Hint: in Python, you can check if a value is an integer with isinstance(value, int). You can check if that value is a list with isinstance(value, list)

Hint: try solving simpler problems first. What is the sum of a list that contains only numbers? What is the sum of a list that contains only lists that contain only numbers?

The correct answer is 883 (hover to view.)

Don't spend more than 20 minutes on this. When you're ready to move on, click here. Don't worry; no spoilers on that page!