def cumSum(a): s = 0 cum_list = [] for i in a: s = s + i cum_list.append(s) return cum_list l = eval(input('Enter list items in Square bracket:')) print(cumSum(l))
Output:
Enter list items in Square bracket: [1, 2, 3, 4]
[1, 3, 6, 10]
Explanation
- Function Definition (
def cumSum(a):
):- This line defines a function named
cumSum
that takes one parameter,a
, which is expected to be a list of numbers.
- This line defines a function named
- Initialize Variables (
s=0
andcum_list=[]
):s
is initialized to 0. This variable will be used to keep track of the cumulative sum.cum_list
is initialized as an empty list. This list will store the cumulative sums at each step.
- Loop Through Each Element (
for i in a:
):- The
for
loop iterates over each elementi
in the input lista
.
- The
- Update Cumulative Sum (
s = s + i
):- For each element
i
, the value ofi
is added tos
, updating the cumulative sum.
- For each element
- Append to Cumulative List (
cum_list.append(s)
):- The updated value of
s
is appended to thecum_list
.
- The updated value of
- Return Cumulative List (
return cum_list
):- After the loop completes, the function returns the
cum_list
containing the cumulative sums.
- After the loop completes, the function returns the
Example
Let’s go through an example. If the input list is [1, 2, 3, 4]
, the function will perform the following steps:
- Initialize
s
to 0 andcum_list
to an empty list. - Iteration 1:
i = 1
, updates
to0 + 1 = 1
, append1
tocum_list
->cum_list = [1]
. - Iteration 2:
i = 2
, updates
to1 + 2 = 3
, append3
tocum_list
->cum_list = [1, 3]
. - Iteration 3:
i = 3
, updates
to3 + 3 = 6
, append6
tocum_list
->cum_list = [1, 3, 6]
. - Iteration 4:
i = 4
, updates
to6 + 4 = 10
, append10
tocum_list
->cum_list = [1, 3, 6, 10]
.
So, the output for the input list [1, 2, 3, 4]
would be [1, 3, 6, 10]
.