1

What's the best way to add the first element in an array to the next element in the same array, then add the result to the next element of the array, and so on? For example, I have an array:

s=[50, 1.2658, 1.2345, 1.2405, 1.2282, 1.2158, 100]

I would like the end array to look like the following:

new_s=[50, 51.2658, 52.5003, 53.7408, 54.969, 56.1848, 100]

Thus leaving the minimum and maximum elements of the array unchanged.

I started going this route:

arr_length=len(s)
new_s=[50]

for i, item in enumerate(s):
     if i == 0:
         new_s.append(new_s[i]+s[i+1])
     elif 0<i<=(arr_length-2):
         new_s.append(new_s[i]+s[i+1])

Currently I get the following list:

new_s=[50, 51.2658, 52.5003, 53.7408, 54.969, 56.1848, 156.1848]

What am I doing wrong that isn't leaving the last item unchanged?

2
  • @AndrewL. He does not want to change the last element Commented Jul 31, 2016 at 19:08
  • Didn't see that, my mistake @VaibhavBajaj Commented Jul 31, 2016 at 19:10

2 Answers 2

1

The beset way is using numpy.cumsum() for all of your items except the last one then append the last one to the result of cumsum():

>>> import numpy as np
>>> s=[50, 1.2658, 1.2345, 1.2405, 1.2282, 1.2158, 100]
>>> 
>>> np.append(np.cumsum(s[:-1]), s[-1])
array([  50.    ,   51.2658,   52.5003,   53.7408,   54.969 ,   56.1848,
        100.    ])

Or with python (3.X) use itertools.accumulate():

>>> import itertools as it
>>> 
>>> list(it.accumulate(s[:-1])) + s[-1:]
[50, 51.2658, 52.500299999999996, 53.74079999999999, 54.968999999999994, 56.184799999999996, 100]
Sign up to request clarification or add additional context in comments.

6 Comments

I am afraid this is not what he wants. He wants the last element to stay the same
He isn't using numpy, so why the extra library?
@AndrewL. Just updated the answer. I just tried to give the best answer.
I'm just not sure why you need an external library to accomplish this. Sure, it's easier, but the OP doesn't mention the use of numPy
Works great! Thanks, it's also much cleaner than my loop.
|
1

You can use numpy.cumsum():

import numpy as np
np.append(np.cumsum(s[:-1]), s[-1])
# array([50., 51.2658, 52.5003, 53.7408, 54.969 , 56.1848, 100.])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.