RECR-P6

Parcels inside parcels

Practice 6 of 6Recursion and backtracking7 tests

The problem

Parcels are packed inside parcels. nested is a list whose items are whole numbers or more lists like it, nested to any depth. The depth of a number is how many lists it is inside: a number directly in nested has depth 1, a number in a list inside nested has depth 2, and so on. Return the sum of every number multiplied by its depth. Do not change nested.

depth_sum([1, [2, [3, 4]], 5])
# 1×1 + 2×2 + 3×3 + 4×3 + 5×1 = 31
depth_sum([[], [[]], [1, []]])    # 1×2 = 2

One test is nested 2,000 levels deep. Read lesson 6 before you start.

Limits

  • Up to 100,000 numbers, and nesting up to 2,000 deep.

Builds on RECR-6 Recursion to iteration.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

7 tests, not run yet
Test results
#TestResultReads · time
1Nested parcelsNot run
2EmptyNot run
3Empty inner listsNot run
4Already flatNot run
5Input not changedNot run
62,000 levels deepNot run
7100,000 numbersNot run