Prefix sum array in Python using accumulate function

We are given an array, find prefix sums of given array.

Examples:

Input : arr = [1, 2, 3]
Output : sum = [1, 3, 6]

Input : arr = [4, 6, 12]
Output : sum = [4, 10, 22]

A prefix sum is a sequence of partial sums of a given sequence. For example, the cumulative sums of the sequence {a, b, c, …} are a, a+b, a+b+c and so on. We can solve this problem in python quickly using accumulate(iterable) method.

filter_none

edit
close

play_arrow

link
brightness_4
code

# function to find cumulative sum of array
from itertools import accumulate
  
def cumulativeSum(input):
      print ("Sum :", list(accumulate(input)))
  
# Driver program
if __name__ == "__main__":
    input = [4, 6, 12]
    cumulativeSum(input)

chevron_right


Output:

Sum = [4, 10, 22]

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.