3

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]

This is almost like a 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
Will
  • 24,082
  • 14
  • 97
  • 108
Jess
  • 33
  • 4

2 Answers2

2
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)
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

You can also use a functional programming pattern:

Try this:

def generateNewArray(inputArray):
    return map(lambda x: sum(inputArray[:x]), xrange(1, len(inputArray) + 1))

For example:

In [7]: generateNewArray([2, 3, 1])
Out[7]: [2, 5, 6]
Will
  • 24,082
  • 14
  • 97
  • 108