Kodewick
开始学 →
基础←→0 / 80

礼盒里的糖

#065基础递归列表约 4 分钟

礼盒里有糖袋(数字,是这袋有几颗),也有小盒子(列表),小盒子里还能再套盒子。写 count_candy(box),数出一共几颗糖。空盒子是 0 颗。

示例
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):
            # 在这里写:碰到小盒子,就把它里面的糖数出来加到 total
            pass
        else:
            total += thing
    return total
Ctrl + Enter 也能运行
结果

写好了先点「运行」试试示例,没问题再点「提交」。