禮盒裡有糖袋(數字,是這袋有幾顆),也有小盒子(列表),小盒子裡還能再套盒子。寫 count_candy(box),數出一共幾顆糖。空盒子是 0 顆。
count_candy([3, [2, 1], 4])→10count_candy([])→0def count_candy(box):
total = 0
for thing in box:
if isinstance(thing, list):
# 在這裡寫:碰到小盒子,就把它裡面的糖數出來加到 total
pass
else:
total += thing
return total
寫好了先點「執行」試試示例,沒問題再點「提交」。