Add up disk usage across servers
Problem statement
You have the used disk space, in GB, for each server in a cluster: usage = [120, 340, 75, 410]. Use a loop to add them up and print:
Total: 945 GB
Examples
Example 1
Input: usage = [120, 340, 75, 410]
Output: Total: 945 GB
Hints
Approach
Optimal
This is the accumulator pattern, one of the most common patterns in programming. Before the loop, create a variable that holds the running result, starting at 0. The for loop visits each number in the list, and total += gb adds it to the running total (+= is shorthand for total = total + gb). When the loop ends, total holds the sum, and you print it once, outside the loop. Python also has a built-in sum(usage) that does the same thing, but writing the loop yourself teaches the pattern you will reuse for counting, finding maximums and building reports.
usage = [120, 340, 75, 410] total = 0for gb in usage: total += gb print(f"Total: {total} GB")Follow-up questions
- Also print the average usage per server.
- Count how many servers use more than 100 GB.
Frequently asked questions
If it is inside, it resets to 0 on every pass, and you end up with only the last value. The starting value must be set once, before looping.