Jess Jess - 6 months ago 17
Python Question

Python array algorithm

I'm working on writing a function where an array is given:
arrayA = [2,3,1]
the function needs to return a new array where newArray = [2,5,6]
its almost like the fibonacci function.

newArray[0]=arrayA[0]
newArray[1]=arrayA[0]+arrayA[1]
newArray[2]=arrayA[1]+arrayA[2]+arrayA[3]


heres my code so far, but always end up with a empty list. arrayA is passed in as parameter.

def generateNewArray(A):
A=[]
newArray=[]
for i in range(len(A)):
newArray[i]=A[i]+A(i+1)
return newArray

Answer
print [sum(A[:i]) for i in range(1,len(A)+1)]

I guess ... I think theres actually a cumulative sum builtin somewhere ... or maybe its in numpy

numpy.cumsum(A)
Comments