Kodewick
开始学 →
小挑战←→0 / 80

搬家装箱

#012小挑战函数循环约 8 分钟

搬家时东西按顺序装箱,每个箱子最多装 cap 公斤(不说就是 10)。下一样放不进当前的箱子,就拿一个新箱子。写 count_boxes(weights, cap),返回要几个箱子。每样都不超过 cap;没有东西就是 0 个。

示例
count_boxes([4, 5, 3, 6])→2
count_boxes([])→0
main.py
def count_boxes(weights, cap=10):
    boxes = 0
    current = 0
    for w in weights:
        # 在这里写:还没有箱子或放不下,就拿新箱子(boxes 加 1,current 清零),再把 w 放进去
        pass
    return boxes
Ctrl + Enter 也能运行
结果

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