Prefix sum array in python using accumulate function


Given an array and we have to do the prefix sum array using accumulate function.itertools.accumulate(iterable[, func]) module functions all construct and return iterators. So they should only be accessed by functions or loops that truncate the stream. Make an iterator that returns accumulated sums. Elements may be any addable type including Decimal or Fraction. If the optional function argument is supplied, it should be a function of two arguments and it will be used instead of addition.

Example

Input
Data = [1, 0, 2, 3, 5]
>>> list(accumulate(data)) # running summation
Output
[1, 1, 3, 6, 11]

Algorithm

Step 1: Create list.
Step 2: use list(accumulate( ))) function, its return running total.
Step 3: display total.

Example Code

# Python program to print prefix
# sum array using accumulate function from itertools import accumulate
def summation(A):
   print ("The List after Summation ::>", list(accumulate(A)))
      # Driver program
      if __name__ == "__main__":
      A=list()
      n=int(input("Enter the size of the First List ::"))
      print("Enter the Element of First List ::")
      for i in range(int(n)):
      k=int(input(""))
      A.append(k)
summation(A)

Output

Enter the size of the First List ::5
Enter the Element of First List ::
1
2
3
4
5
The List after Summation ::> [1, 3, 6, 10, 15]

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 25-Jun-2020

342 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements