Count the boxes used when packing in order

Write codeEasy10 min

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 to capacity.
  • 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 exactly capacity is 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) -> int
Example 1
Inputboxes_needed([3, 4, 5, 2], 7)
Output2
Example 2
Inputboxes_needed([3, 3, 3], 5)
Output3