礼盒里有糖袋(数字,是这袋有几颗),也有小盒子(列表),小盒子里还能再套盒子。写 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
写好了先点「运行」试试示例,没问题再点「提交」。