0

I want to sum elements in an array. For example I have an array

[183948, 218520, 243141, 224539, 205322, 203855, 233281, 244830, 281245,
 280579, 235384, 183596, 106072,  88773,  63297,  38769,  28343]

I want to sum it in three different parts which are the first three elements, the next 10 elements and the rest. My only idea is to separate the array and use sum method. Is there better way to do it? Thanks in advance!

5
  • Slice the array and sum the slices. Since it seems your partitioning of the array is arbitrary, there's not going to be a truly elegant solution. Perhaps you can put your slice indices into a list and use a for loop to go through them Commented Jun 22, 2019 at 9:40
  • slice and sum is best way Commented Jun 22, 2019 at 9:48
  • Got it, this is what I was thinking too Commented Jun 22, 2019 at 10:37
  • @roganjosh have you answered my question before? your name seems familiar? Commented Jun 22, 2019 at 10:37
  • My name probably is familiar; I spend too much time here. Commented Jun 22, 2019 at 11:32

2 Answers 2

1

try this:

arr=[183948, 218520, 243141, 224539, 205322, 203855, 233281, 244830, 281245,
 280579, 235384, 183596, 106072,  88773,  63297,  38769,  28343]

first=arr[0:3]
second=arr[3:13]
last=arr[13:]

print(sum(first))
print(sum(second))
print(sum(last))

the alternative more extensible version is as follows

arr=[183948, 218520, 243141, 224539, 205322, 203855, 233281, 244830, 281245,
 280579, 235384, 183596, 106072,  88773,  63297,  38769,  28343]

indices=[3,13]
results=[]
prev=0
for i in indices:
    results.append(sum(arr[prev:i]))
    prev=i
results.append(sum(arr[prev:]))

for res in results:
    print(res)

note: set prev = to the index you want to start from, in this case 0

Sign up to request clarification or add additional context in comments.

3 Comments

I think this is the only way, but a vast improvement would be having the indices in a list and iterating with a for loop. This is hard-coded.
that works too but i think for only 3 slices this is ok. if he had more slice points then that way would def be alot better tho
Ok, but would it not be better to post an extensible answer? What if someone else comes along that has 10 slices?
0

You can use the reduceat method of np.add:

data = [183948, 218520, 243141, 224539, 205322, 203855, 233281, 244830, 281245,
 280579, 235384, 183596, 106072,  88773,  63297,  38769,  28343]

sizes = 3, 10

np.add.reduceat(data, np.cumsum([0, *sizes]))
# array([ 645609, 2198703,  219182])

1 Comment

What should I do if sizes is zero? e.g. sizes = 3, 0, 10 which returns array([ 645609, 224539, 2198703, 219182]), even though the desired result would be array([ 645609, 0, 2198703, 219182])

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.