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.
# 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
filter_none
Output:
Sum = [4, 10, 22]
Recommended Posts:
- Rearrange the array to maximize the number of primes in prefix sum of the array
- Count the number of primes in the prefix sum array of the given array
- Prefix Sum of Matrix (Or 2D Array)
- Python | Prefix sum list
- Longest prefix that contains same number of X and Y in an array
- Python | Get numeric prefix of given string
- Python | Prefix key match in dictionary
- Python | Get the numeric prefix of given string
- Prefix matching in Python using pytrie module
- Python | Prefix extraction before specific character
- Python | Remove prefix strings from list
- Python | Merging two strings with Suffix and Prefix
- Python | Prefix Sum Subarray till False value
- Prefix Sum Array - Implementation and Applications in Competitive Programming
- Maximum array sum with prefix and suffix multiplications with -1 allowed
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.