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!
CodePudding user response:
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:])))
CodePudding user response:
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]
CodePudding user response:
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]]
CodePudding user response:
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)