# [Numpy-discussion] reverse cumsum?

Joshua Holbrook josh.holbrook@gmail....
Tue Jul 6 14:37:02 CDT 2010

```On Tue, Jul 6, 2010 at 11:25 AM, Jonathan Stickel <jjstickel@vcn.com> wrote:
> On 7/6/10 10:42 , numpy-discussion-request@scipy.org wrote:
>> Date: Tue, 06 Jul 2010 10:02:57 -0400
>> From: Alan G Isaac<aisaac@american.edu>
>> Subject: Re: [Numpy-discussion] reverse cumsum?
>> To: Discussion of Numerical Python<numpy-discussion@scipy.org>
>> Message-ID:<4C333791.5010505@american.edu>
>> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>>
>> On 7/6/2010 9:56 AM, Ken Basye wrote:
>>> >  Is there a simple way to get a cumsum in reverse order?
>>>>> >>>  x = np.arange(10)
>>>>> >>>  x[::-1].cumsum()[::-1]
>> array([45, 45, 44, 42, 39, 35, 30, 24, 17,  9])
>>
>> Is that what you want?
>>
>> Alan Isaac
>
> Or, you can do:
>
> In [1]: a = np.arange(10)
> In [5]: np.sum(a) - np.cumsum(a)
> Out[5]: array([45, 44, 42, 39, 35, 30, 24, 17,  9,  0])
>
> Jonathan
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>

Alternately:

In [11]: reversed(np.arange(10).cumsum())
Out[11]: <reversed object at 0x8b9d14c>

In [12]: [i for i in _]
Out[12]: [45, 36, 28, 21, 15, 10, 6, 3, 1, 0]

reversed(x) is, as you can see, not an array but an iterator which
will return the cumulative sums in reverse. If you need an array
specifically, you can convert it fairly easily, though it does need
two type conversions:

In [10]: np.array(list(reversed(np.arange(10).cumsum())))
Out[10]: array([45, 36, 28, 21, 15, 10,  6,  3,  1,  0])

or, if you like list comps:

In [14]: np.array([i for i in reversed(np.arange(10).cumsum())])
Out[14]: array([45, 36, 28, 21, 15, 10,  6,  3,  1,  0])

I think Ken's suggestion may be the best so far, but as perl users
say, timtowtdi.

--Josh
```