Running sum using accumulate in Python

in #python5 years ago

Given a array in Python, we can use a for loop to make a running sum in place.
For example

arr = [1, 2, 3, 4, 5]
for i in range(1, len(arr)):
   arr[i] += arr[i - 1]

The arr now will contains all the running sum i.e. [1, 3, 6, 10, 15].

We can import the accumulate function from itertools:

arr = list(accumulate(arr))

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Thank you for reading ^^^^^^^^^^^^^^^

NEW! Following my Trail (Upvote or/and Downvote)

Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

My contributions

Delegation Service

Important Update of Delegation Service!

  • Delegate 1000 to justyy: Link
  • Delegate 5000 to justyy: Link
  • Delegate 10000 to justyy: Link

Support me

If you like my work, please:

  1. Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
  2. Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
  3. Set @justyy as Proxy: https://steemyy.com/witness-voting/?witness=justyy&action=proxy
    Alternatively, you can vote witness or set proxy here: https://steemit.com/~witnesses

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.082
BTC 60235.88
ETH 1578.52
USDT 1.00
SBD 0.42