Count the boxes used when packing in order
Your task
A packing station fills shipping boxes from a conveyor. Items must stay in conveyor order, and the station never goes back to a sealed box.
Write boxes_needed(weights, capacity) that returns how many boxes the station uses.
Input and output:
weights: the item weights in conveyor order, a list of 0 to 100,000 integers, each from 1 tocapacity.capacity: the most weight one box holds, an integer from 1 to 1,000,000.- Returns the number of boxes used.
Rules:
- The first item opens the first box.
- Each later item goes into the open box if the box's total weight would then be at most
capacity. A box filled to exactlycapacityis fine. - Otherwise the open box is sealed, and the item opens a new box.
- An empty list uses 0 boxes.
Examples
boxes_needed(weights: list[int], capacity: int) -> intExample 1
Input
boxes_needed([3, 4, 5, 2], 7)Output
2Example 2
Input
boxes_needed([3, 3, 3], 5)Output
3