PracticeArrays

Consecutive Cargo Load Totals

BeginnerArraystraversalaccumulationstate tracking Time not estimated Not started

Context

A distribution hub records the cargo weight of each shipment loaded onto a truck, in loading order. The dispatcher wants a new list showing the combined weight of every shipment with the one loaded immediately after it. These are overlapping pairs: each interior shipment contributes to the pair before it and the pair after it.

Problem

Given an integer array shipments representing shipment weights in loading order, return an array containing the sum of each pair of consecutive weights. Preserve pair order from left to right. The first result uses positions 0 and 1, the next uses positions 1 and 2, and so on. Every valid neighboring pair must contribute exactly one result. If fewer than two shipments are recorded, return an empty array.

Examples

Example 1
Input: shipments = [12, 7, 15, 4]
Output: [19, 22, 19]
Explanation: For [12, 7, 15, 4], the executed output is [19, 22, 19], containing one result for each consecutive pair in the original order.
Example 2
Input: shipments = [0, -5, -5, 10]
Output: [-5, -10, 5]
Explanation: For [0, -5, -5, 10], the executed output is [-5, -10, 5], preserving the negative and zero values in the consecutive-pair sums.
Example 3
Input: shipments = [23]
Output: []
Explanation: For the single-element input [23], the executed output is [], because the input has no valid neighboring pair.

Constraints

  • 0 <= len(shipments) <= 1000
  • -1000000 <= shipments[i] <= 1000000 for every i
  • Types: shipments is int[]; result is int[]

Function signature

def consecutive_cargo_totals(shipments: list[int]) -> list[int]
shipments list[int]
Shipment weights listed in loading order.
returns list[int]
The ordered sums for every overlapping pair of consecutive shipment weights, or an empty array when no complete pair exists.

Adapted from MBPP problem task_470 (CC BY 4.0). Rewritten, extended and verified by Iksha.

Approved · cb008-abs_924_v314 execution-verified tests
Code
Saved
Checking environment…Python SandboxLn 1, Col 1