Given a list A of size N, how do I create a list B so that each element of B is the sum of the previous element of both A and B?

Viewed 88

I'm trying to create a function my_function(A), that takes a list A of N numbers, and outputs a list B of N+1 numbers with B[0]=0 and B[n]=B[n-1]+A[n-1] where n<N.

For example, if A is the list [1,2,3,4,5], B[1]=B[0]+A[0]=0+1, B[2]=B[1]+A[1]=1+2 and the final output would be [0,1,3,6,10,15]

I need to use only numpy, at most.

My code is

def my_function(A):
   for n in range(len(A)):
      B[0]=0
      B[n]=B[n-1]+A[n-1]
      return B[n]

I can't find a way to define B without errors

4 Answers

You just need to initalize B corrently:

def my_function(A):
    B = [0] * (len(A) + 1) # list with N + 1 Zeros
    for n in range(1, len(A) + 1): # n in 1..N
        B[n] = B[n-1] + A[n-1]
    return B

or

def my_function(A):
    B = [0] * (len(A) + 1) # list with N + 1 Zeros
    for n in range(len(A)): # n in 0..N-1
        B[n+1] = B[n] + A[n]
    return B

Slightly more python is to use itertools.accumulate:

from itertools import accumulate

def my_function(A):
    return [0, *accumulate(A)] # accumulate doesn't start with 0

You can use np.cumsum:

result = np.r_[0, np.cumsum(A)]

np.r_ is a shorthand for np.concatenate(..., axis=-1):

result = np.concatenate(([0], np.cumsum(A)), axis=1)

np.cumsum itself is a shorthand for np.add.accumulate:

result = np.r_[0, np.add.accumulate(A)]

By implementing the loops in C, vectorized operations will almost always run faster than a python level loop.

You can try this:

def my_function(A):
    B = [0]
    n=1
    while n < len(A):
        B.append(B[n-1]+A[n-1])
        n+=1
    return B

You need to initialize a List 'B' before
This May be you answer -

A = [1,2,3,4,5] 
B = [None]*5
def my_function(A):
    B[0]=0
    for n in range(len(A)):
        if n==0:
            continue
        else:
            B[n]=B[n-1]+A[n-1]

Then Just Use "B".

Related