Python · Level 2 Algorithms

Recursion

Some problems contain smaller copies of themselves. Solve them with a function that calls itself until it reaches a simple base case.

  • Base case and recursive case
  • isinstance() to check types
  • Processing nested data of any depth

A recursive function handles the simple case directly and hands smaller pieces of the problem back to itself.

def total(nested):
    result = 0
    for item in nested:
        if isinstance(item, list):
            result += total(item)   # recursive case
        else:
            result += item          # base case
    return result

total([1, [2, [3]]])   # -> 6

Write flatten(nested) that returns a flat list of every non-list item in nested, in order, however deeply the lists are nested.

solution.py
Test Suites Pending
Stdout