Open In App

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. 

Implementation:




# 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)

Output
Sum : [4, 10, 22]

The time complexity of this cumulativeSum function is O(n), where n is the length of the input array.

The auxiliary space complexity of this function is also O(n), where n is the length of the input array.

Article Tags :