Code

Treasure in Nested Chests

Recursion shines on data that contains smaller copies of itself: folders inside folders, comments with replies, chests inside chests.

def count_items(chest):
    total = 0
    for thing in chest:
        if isinstance(thing, list):
            total += count_items(thing)  # a smaller chest!
        else:
            total += 1
    return total

print(count_items(["gem", ["coin", ["ring"]], "map"]))  # 4

A loop handles the items side by side; recursion handles the items inside each other. Here the base case is hidden: a chest with no inner chests simply never recurses.

Assignment

A chest is a list that holds whole numbers (gem values) and other chests.

  1. count_gems(chest) returns the total value of every gem, however deep. count_gems([5, [10, [1, 2]], 3]) is 21.
  2. deepest(chest) returns how many levels of chests there are. deepest([1, 2]) is 1, deepest([1, [2, [3]]]) is 3, deepest([]) is 1.