Reputation: 45
I'm very new to python. I'm trying to create a loop so that I can get cumulative sums of the elements in a list. For example, given a list [3, 2, 1] I'm hoping to get [3 (first number), 5 (3+2), 6 (3+2+1)], [2 (second number), 3 (2+1)] and [1].
What I have currently is:
data = [5, 4, 3, 2, 1]
for i in data:
perf = [sum(data[:i+1]) for i in range(len(data))]
print(perf)
And I'm getting the following as output, which is the sum from the first element. How do I modify to get the cumulative sums starting with 4, 3, ... ?
[5, 9, 12, 14, 15]
[5, 9, 12, 14, 15]
[5, 9, 12, 14, 15]
[5, 9, 12, 14, 15]
[5, 9, 12, 14, 15]
My desired output
[5, 9, 12, 14, 15]
[4, 7, 9, 10]
[3, 5, 6]
[2, 3]
[1]
Thank you!
Upvotes: 2
Views: 773
Reputation: 1520
Your statement to compute a commulative sum within the loop is correct.
You had just used i
incorrectly in the outer loop statement.
All you need to do is slice your original data and generate sums for each slice.
test_data = [5, 4, 3, 2, 1]
def commulative_sum(a_list: list[int]):
# The same thing you wrote
return [sum(a_list[:i+1]) for i in range(len(a_list))]
def commulative_sums(data: list[int]):
# Slice the input data and generate commulative sums
return [commulative_sum(data[j:]) for j in range(len(data))]
result = commulative_sums(test_data)
print(result)
[[5, 9, 12, 14, 15], [4, 7, 9, 10], [3, 5, 6], [2, 3], [1]]
Upvotes: 1
Reputation: 245
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]
Upvotes: 1
Reputation: 195528
If I understand you correctly, in the 1. iteration you want to get sums from first element, in the 2. iteration sums from second element and so on:
data = [5, 4, 3, 2, 1]
for i in range(len(data)):
s = 0
l = [s := s + d for d in data[i:]]
print(l)
Prints:
[5, 9, 12, 14, 15]
[4, 7, 9, 10]
[3, 5, 6]
[2, 3]
[1]
Or: using itertools.accumulate
from itertools import accumulate
data = [5, 4, 3, 2, 1]
for i in range(len(data)):
print(list(accumulate(data[i:])))
Upvotes: 2
Reputation: 1353
Here are 2 ways you can solve this problem.
data = [5, 4, 3, 2, 1]
k = 0;
for i in data:
k = k + i
print(k)
And this is the second method
data = [5, 4, 3, 2, 1]
k = 0;
for i in range(len(data)):
k = k + data[i]
print(k)
Upvotes: 0