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
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | Nested parcels | Not run | |
| 2 | Empty | Not run | |
| 3 | Empty inner lists | Not run | |
| 4 | Already flat | Not run | |
| 5 | Input not changed | Not run | |
| 6 | 2,000 levels deep | Not run | |
| 7 | 100,000 numbers | Not run |