Kodewick
開始學 →
基礎←→0 / 80

禮盒裡的糖

#065基礎isinstance(thing, list)約 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 也能執行
結果

寫好了先點「執行」試試示例,沒問題再點「提交」。