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

One number for the whole fleet

Every server hands you one count and the question wants a single number back. Folding many values into one is a reduction, and the tool for it is an accumulator: a variable that exists before the loop, absorbs each value, and holds the answer when the loop ends. Totals, maxima, running balances and row tallies are all built this way, so the pattern you write over counts here is one you will reuse constantly.

Folding counts into total

Step 1: Seed total with 0

0 is the identity for addition: adding it changes nothing. Starting there means a fleet with no servers reports 0 events without any special case.

Step 2: Visit each server's count once

for value in counts hands you the values directly. You never need a position, so there is no index to manage and no range(len(counts)) to get wrong.

Step 3: Add inside, return outside

total += value keeps everything seen so far. return total sits at the function's own indentation, after the loop, so it fires only once every server has been counted.

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

On [1, 2, 3, 4, 5], total moves through 1, 3, 6, 10, 15 and the function returns 15. On [10] the loop runs once and returns 10.

A total that forgets earlier servers

The seed moved inside the loop
def sum_list(counts):
    for value in counts:
        total = 0
        total += value
    return total

Returns 5 on [1, 2, 3, 4, 5] and 10 on [10].

Seed from `counts[0]`
total = counts[0] followed by a loop over counts[1:] gives 15 on the first example, then raises IndexError the day the list arrives empty. The slice also copies the list.
Seed from 0
total = 0 and a loop over all of counts gives the same 15, returns 0 for an empty fleet, and reads the list in place.

The built-in sum does this loop

Python ships this exact loop as sum. In a pipeline you call it. In an interview, write the loop first so it's clear you know what happens underneath, then say the built-in exists.

The same total with the built-in
def sum_list(counts):
    return sum(counts)

Same 15 and 10 on the examples, and 0 on an empty list.

Common follow-up questions