How to Find the Cumulative Sum of Numbers in a List

How to find the cumulative sum of numbers in a list by adding a constant value?

As you specifically mentioned numpy:

import numpy as np

initial_value = 5
constant_value = 3
desired_list_size = 7

result = np.arange(desired_list_size) * constant_value + initial_value

This starts with a range from 0 to 7 (exclusive) then it multiplies each element by 3 and in the end it adds 5 to each element.

Note: the result size is actually equal to desired_list_size and not one larger as in your question.

Loop through list elements to get cumulative sums

You're not far from the answer. You just need to begin your range from the next num in the list. Try this:

data = [5, 4, 3, 2, 1]
for ind, num in enumerate(data):
perf = [sum(data[ind:i+1]) for i in range(ind, len(data))]
print(perf)

Output:

[5, 9, 12, 14, 15]
[4, 7, 9, 10]
[3, 5, 6]
[2, 3]
[1]

Python Running Sum in List

If you'd like a numpy solution

from numpy import cumsum
result = list(cumsum(a))

Modified cumulative sum of numbers in a list

This should solve your problem:

def changelist (l, t):
subset = sum(l) / t
current, total = 0, 0
for x in l:
total += x
if total > subset:
current, total = current + 1, x
yield current

Examples:

>>> list(changelist([1, 4, 5], 2))
[0, 0, 1]
>>> list(changelist([1, 2, 3, 4, 2, 5, 1, 6], 4))
[0, 0, 0, 1, 1, 2, 2, 3]
>>> list(changelist([1, 2, 3, 4, 2, 5, 1, 6], 2))
[0, 0, 0, 0, 0, 1, 1, 1]

How does it work?

  • current stores the "id" of the current subset, total the sum of the current subset.
  • For each element x in your initial list l, you add its value to the current total, if this total is greater than the expected sum of each subset (subset in my code), then you know that you are in the next subset (current = current + 1) and you "reset" the total of the current subset to the actuel element (total = x).


Related Topics



Leave a reply



Submit