Sum an arbitrarily nested integer list

Problem

Implement nested_total(value) where value is either an integer or a list containing more valid values. Lists may be empty and nesting depth is arbitrary. Do not use loops, sum, or slicing.

Reveal answer or reference solution

Use one base case for an integer and a second base case for reaching the end of a list. Recursively total the current child and the remainder by index. Every integer and list position is processed once; stack depth depends on both nesting and list length.

def nested_total(value: int | list) -> int:
    if isinstance(value, int):
        return value
 
    def total_from(index: int) -> int:
        if index == len(value):
            return 0
        return nested_total(value[index]) + total_from(index + 1)
 
    return total_from(0)

Public tests

  • nested_total(7) → 7
  • nested_total([]) → 0
  • nested_total([1, [2, [], [3]], 4]) → 10
  • nested_total([[-2], [5, [-1]]]) → 2
  • nested_total([[[[0]]]]) → 0
Outcome

Previous attempts

Loading attempts saved in this browser…

    Review Screening Results