All Told

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L3

Problem

Given counts, where each value is the number of events one server logged during a shift, return the fleet's combined total.

Every shift leaves a number behind. Total the fleet.

Example 1

Input:

counts = [1,2,3,4,5]

Output:

15

Example 2

Input:

counts = [10]

Output:

10

Worked solution and explanation

What's really being tested

This is a running total over a list whose length you don't control, dressed up as a fleet report. Nobody fails on the arithmetic; what separates candidates is whether the code survives a fleet of one and counts that can go negative. Hardcode counts[0] + counts[1] and a single-server shift raises an IndexError while a three-server shift comes back 300 short. Reach for len or max instead and a shift of [-5, 5] reports 2 or 5 where the real total is 0.


The two decisions

Step 1: Start the total at zero

Zero is the identity for addition, so an empty-looking accumulator can't poison the result. Start it at the wrong value and every answer is off by a constant nobody notices until the totals look subtly wrong in prod.

Step 2: Fold each value in

Walk the list once and add each count to the running total. One pass, every element touched exactly once: there is no reason to index by position or build a second list.


The solution

Linear accumulation with a running total
def sum_list(counts):
    total = 0
    for value in counts:
        total += value
    return total

Common follow-up questions