0

I would like to define a function where you input multiple numbers and the function will add up the first two, and then add the answer to the third, then the answer to this to the fourth and so on until the numbers have all been incrementally added up. For example:

def function(x1, x2, x3, x4):
    ind_1 = x1 + x2
    ind_2 = ind_1 + x3
    ind_3 = ind_2 + x4
    return x1, ind_1, ind_2, ind_3

function(175, 107, 107, 95)

OUT: (175, 282, 389, 484)

How could I scale this up so it does it repeatedly on a generic list of numbers which change every time I use it without having to manually write out all the sums in the function?

Thanks!

LM1995
  • 1
  • 1

3 Answers3

1
import itertools

def function(*args): 
    return list(itertools.accumulate(args))

accumulate does exactly what you want, see other examples in the documentation. You do not have to make a list from the returned generator if you only want to iterate over it.

Edit: removed operator.add thanks to @PaulPanzer's comment.

Luka Mesaric
  • 657
  • 6
  • 9
0

For that there is defined function in numpy: cumsum

import numpy as np
x = np.array([175, 107, 107, 95])
x.cumsum()

Output:

array([175, 282, 389, 484])
Code Pope
  • 5,075
  • 8
  • 26
  • 68
0

To do this yourself you need a special expansion syntax * on the function's input arguments to allow to pass an arbitrary number of arguments into a list.

def f(*nums):
  s=0
  out=[]
  for n in nums:
    s+=n
    out.append(s)
  return out

See: Can a variable number of arguments be passed to a function?

jpf
  • 1,447
  • 12
  • 22