2

So I have an array [1,2,3,4,5,6,7,8,9,10] and I need to create a new array that adds together the first5 elements then the next 5 elements, ect. so 1+2+3+4+5=15, 6+7+8+9+10=40 [15,40]. How would i go about doing this?

Md. Rezwanul Haque
  • 2,882
  • 7
  • 28
  • 45
D B
  • 33
  • 5
  • Use [`sum`](https://docs.python.org/3/library/functions.html#sum) and https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks – Artyer Jul 26 '17 at 17:36
  • 1
    Is it always going to be the first 5, then the next 5? What if it is a list with more than 10 elements. What then? Furthermore, the link provided by Artyer I think is incorrect for this example. Please show what you have tried. StackOverflow is not a code-writing service. You need to show your efforts in the form of a clear [mcve]. – idjaw Jul 26 '17 at 17:38
  • Well i have a code i'm running and it's used to analyze and plot out a set of values when they are all added together, I just have no clue how to ask the question, and showing my code probably wouldn't help. I guess i could post it though if you really want me to prove its not just a homework question or something. – D B Jul 26 '17 at 17:47
  • @DB you actually did a really good job explaining what you are trying to do. If you tried to isolate the part of your code that attempts to do that slicing and explain what is happening around it, that would have been awesome. – idjaw Jul 26 '17 at 17:50

5 Answers5

4

you can do something like :

>>> l1 =  [1,2,3,4,5,6,7,8,9,10]
>>> l2= [sum(l[n:n+5]) for n in range(0, len(l), 5)]
>>> l2
[15, 40]
Dadep
  • 2,796
  • 5
  • 27
  • 40
1

You can do something like that:

def sumEach5Element(input):
  o = []
  for i in range(0, len(input), 5):
    o.append(sum(input[i:i+5]))

  print(o)  

sumEach5Element([1,2,3,4,5,6,7,8,9,10])
Deepak Singh
  • 411
  • 1
  • 5
  • 13
1

You can follow this process :

arr1 = [1,2,3,4,5,6,7,8,9,10]
arr2 = [sum(arr1[:len(arr1)//2]), sum(arr1[len(arr1)//2:])]
print(arr2)
# output :
[15, 40]
Md. Rezwanul Haque
  • 2,882
  • 7
  • 28
  • 45
0

Simple solution (I also considered an array which has a number of elements not divisible by 5):

my_array =  [1,2,3,4,5,6,7,8,9,10,11]
output_array = []
for i in range(len(my_array)/5): 
   tmp = my_array[i*5:(i+1)*5]
   output_array.append(sum(tmp))

# check if you can divide by 5
mod = len(my_array)%5
if mod > 0:
   output_array.append(sum(my_array[-mod::]))  
0
arr = [1,2,3,4,5,6,7,8,9,10] 

def addList(sub): 
  result = sum(list(sub))
  return result

def breakTheList(arr, num):
    for i in range(0, len(arr), num):
        subDiv = arr[i:i + num]
        print(addList(subDiv))

breakTheList(arr, 5)
# 15 40

The above code will work with breaking the list into as many pieces as you like and add those pieces. Here is another example

breakTheList(arr, 4)
#10 26 19
Boshika Tara
  • 234
  • 2
  • 4