4

I need to add the first three elements of a list then add the next three elements of a list and so forth. This is the code I have got so far:

def get_triple_sums_list(a_list):
    new_list = []
    for numbers in range(0,len(a_list)):
        numbers = sum(a_list[:3])
        new_list.append(numbers)
        return new_list
    if a_list == []:
        return []

For the list:

 [1, 5, 3, 4, 5, 2]

This in turn gives me the result:

[9]

I need to get

[9, 11]

If the remaining numbers is less than 3, it gives me the remainder of the sum ie,

[1, 6, 2, 4, 3]

Gives me

[9, 7]

And

[1, 6, 2, 4]

Give me

[9, 4]
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
R. Mercy
  • 509
  • 1
  • 5
  • 21

6 Answers6

3

Let's analyze your code!

def get_triple_sums_list(a_list):
    new_list = []
    for numbers in range(0,len(a_list)):
        numbers = sum(a_list[:3]) #You should be using the variable
                                  #numbers here somehow.
       #^^^^^^^ - You are overwriting the for-loop index.
        new_list.append(numbers)
        return new_list  #Why are you returning here? You should be
                         #appending to `new_list`.
    if a_list == []:
        return []

Here is the fixed code:

def get_triple_sums_list(a_list):
    new_list = []
    for index in range(0,len(a_list), 3): #Range takes a 3rd param!
        total = sum(a_list[index:index+3])#Get all the elements from the
                                          #index to index+3
        new_list.append(total)
    return new_list

UPDATE: It seems there's a shortening contest going on -- and I do not want to be left behind. Here's an ugly version I'd like to add to the list.

>>> a = [1,2,3,4,5,6,7,8]
>>> a += [0]*(len(a)%3) #For people who are too lazy to import izip_longest
>>> map(sum,zip(a[::3], a[1::3], a[2::3]))
[6, 15, 15]
UltraInstinct
  • 43,308
  • 12
  • 81
  • 104
2

I like SuperSaiyan's approach of explaining things, I'll be the one who shortens it a bit. You can get the same result with a single comprehension:

l = [1, 5, 3, 4, 5, 2]
n = 3    
r = [sum(l[i:i+n]) for i in range(0, len(l), n)]

print(r)
[9, 11]

l[i:i+n] splits the list in even chunks of length 3 and sum takes care of adding these together. Using the for i in range(0, len(l), n) we dictate that this operation is to happen for ceil(len(l) / 3) times.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
1

Just cuz I like to be different.

l = [1, 5, 3, 4, 5, 3, 42]
g = lambda l,s: [sum(l[i:i+s]) for i in range(0,len(l),s)]
print g(l,3)

#>> [9,12,42]
kpie
  • 9,588
  • 5
  • 28
  • 50
  • This is almost the same answers as others, but with a lambda wrapped on the outside. – UltraInstinct Oct 03 '16 at 09:45
  • Really? That's funny, it's the same question... – kpie Oct 04 '16 at 15:18
  • http://stackoverflow.com/questions/26939931/moving-non-overlapping-window-in-numpy http://stackoverflow.com/questions/25879735/how-to-implement-a-function-with-non-overlapping-and-rolling-features-simultaneo http://stackoverflow.com/questions/21097039/average-on-overlapping-windows-in-python – kpie Oct 04 '16 at 15:22
0

The other answer mentions the fault with your code. However do note that it's always easier to use a list comprehension in these cases.

>>> l =  [1, 5, 3, 4, 5, 2]
>>> [sum(l[i:i+3]) for i in range(0,len(l),3)]
[9, 11]

It also works for un-mod-3 lists

>>> l =  [1, 5, 3, 4, 5]
>>> [sum(l[i:i+3]) for i in range(0,len(l),3)]
[9, 9]

See What does "list comprehension" mean? How does it work and how can I use it? for more details about a list comprehension.

Community
  • 1
  • 1
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
0

Alternatively, you may achieve it by using map() with lambda function as:

>>> my_list = [1, 5, 3, 4, 5, 2]
>>> list(map(lambda x: sum(my_list[x:x+3]), range(0, len(my_list), 3)))
[9, 11]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
  • You could just say: `[sum(my_list[i:i+3]) for i in range(0, len(my_list), 3)]` – UltraInstinct Oct 03 '16 at 09:44
  • It was already answered here. However removed that solution, as it was not the right way to do it even though it was working – Moinuddin Quadri Oct 03 '16 at 10:07
  • In my opinion, it is a more pythonic way of achieving the same thing. I am not sure why you'd consider it wrong. (List comprehension is more *pythonic* than map/lambda combination) – UltraInstinct Oct 03 '16 at 10:10
  • Yes. I agree on that. I meant that the solution with *list comprehension* is already mentioned here. That's why I haven't mentioned that. Instead the one I removed was having list comprehension + map, which was not at all pythonic. – Moinuddin Quadri Oct 03 '16 at 10:18
0

Here is a slightly different way of doing it using zip_longest from itertools (izip_longest in python2), it splits the list in three lists then zip them to get packs of three elements and finally sums the packs:

from itertools import zip_longest
a=[1, 6, 2, 4, 3]
b=zip_longest(a[0::3],a[1::3],a[2::3],fillvalue=0)
result=[sum(x) for x in b]
>>>[9, 7]
jadsq
  • 3,033
  • 3
  • 20
  • 32