Running total
Write running_total(nums) that returns a new list where each item is the sum of all items up to and including that position.
running_total([1, 2, 3, 4]) # [1, 3, 6, 10]
running_total([5, -2, 7]) # [5, 3, 10]
running_total([]) # []
Show hint
Keep one variable holding the total so far, and append it after each step.
Show solution
def running_total(nums):
out = []
total = 0
for n in nums:
total += n
out.append(total)
return out
This is the accumulator pattern: one pass, O(n) time. The standard library has it built in as list(itertools.accumulate(nums)). Running totals (also called prefix sums) are a key trick for answering "sum of a range" questions quickly.
Want a problem like this every day? See today's problem and keep a streak going.