Kodewick
Start learning →
Basic←→0 / 80

Boxes of sweets

#065BasicRecursionLists4 min

A gift box holds bags of sweets (numbers: how many in the bag) and smaller boxes (lists), and those boxes can hold boxes too. Write count_candy(box) to count all the sweets. An empty box has 0.

Examples
count_candy([3, [2, 1], 4])→10
count_candy([])→0
main.py
def count_candy(box):
    total = 0
    for thing in box:
        if isinstance(thing, list):
            # your code here: for a smaller box, count the sweets inside it and add them to total
            pass
        else:
            total += thing
    return total
Ctrl + Enter runs too
Result

Run tries the examples. When they look right, Submit.