Python program that takes list of numbers as input from the user and produces a cumulative list where each element in the list at any position n is sum of all elements at positions up to n-1

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

  1. 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.
  2. Initialize Variables (s=0 and cum_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.
  3. Loop Through Each Element (for i in a:):
    • The for loop iterates over each element i in the input list a.
  4. Update Cumulative Sum (s = s + i):
    • For each element i, the value of i is added to s, updating the cumulative sum.
  5. Append to Cumulative List (cum_list.append(s)):
    • The updated value of s is appended to the cum_list.
  6. Return Cumulative List (return cum_list):
    • After the loop completes, the function returns the cum_list containing the cumulative sums.

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 and cum_list to an empty list.
  • Iteration 1: i = 1, update s to 0 + 1 = 1, append 1 to cum_list -> cum_list = [1].
  • Iteration 2: i = 2, update s to 1 + 2 = 3, append 3 to cum_list -> cum_list = [1, 3].
  • Iteration 3: i = 3, update s to 3 + 3 = 6, append 6 to cum_list -> cum_list = [1, 3, 6].
  • Iteration 4: i = 4, update s to 6 + 4 = 10, append 10 to cum_list -> cum_list = [1, 3, 6, 10].

So, the output for the input list [1, 2, 3, 4] would be [1, 3, 6, 10].

Leave a Reply

Your email address will not be published. Required fields are marked *