-1

I came across this problem when in an interview. The requirement is to realize cumulative sum in one line of python. My answer is

def cum_sum(nums):
    return [sum(nums[0:i+1]) for i in range(len(nums))]

This is very ugly, the previous result has not been used later which results in redundant calculations. I think there must have some high-level way to implement it.

Any help is welcomed. Thanks.

yangcs11
  • 99
  • 1
  • 1
    Does this answer your question? [How to find the cumulative sum of numbers in a list?](https://stackoverflow.com/questions/15889131/how-to-find-the-cumulative-sum-of-numbers-in-a-list) – Julia Aug 09 '20 at 15:29

3 Answers3

4

See accumulate in Python3.2+. That should work.

For your piece of code, the corresponding code would be:

from itertools import accumulate

return list(accumulate(nums)) 

Edit : The updated code is to return a list rather than an iterator.

ghost
  • 1,107
  • 3
  • 12
  • 31
2

You can try the following ways to get a cumulative sum in one line -

nums = [10,20,30,40,50,60,70,80,90,100]

#Using base python 
[sum(nums[0:i[0]+1]) for i in enumerate(nums)]
#OUTPUT - [10, 30, 60, 100, 150, 210, 280, 360, 450, 550]

#Using Numpy
np.cumsum(nums)
#OUTPUT - array([ 10,  30,  60, 100, 150, 210, 280, 360, 450, 550])
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
  • But the complexity has not been reduced. What I want to know is that: To calculate sum(nums[0:n+1]), we could use sum([nums[1:n-1]) + nums[n]. In this way, the number of add operation can be lowered. But I can't find one. – yangcs11 Sep 21 '20 at 09:17
0

Using default value and recursion

Code

def cum_sum(lst, accum=0):
  return [lst[0] + accum] + accumulate(lst[1:], accum + lst[0]) if lst else []

Test

print(cum_sum([1, 2, 3, 4, 5])) # Output: [1, 3, 6, 10, 15]
DarrylG
  • 16,732
  • 2
  • 17
  • 23