1

My last question was adding two consecutive numbers in a list . But answers are not generalized. How to add n consecutive elements in a list. where n >= 2

if n = 3

l = [1,2,3,4,5,6] result = [6, 15]
l = [1,2,3,4,5,6,7] result = [6, 15, 7]
l = [1,2,3,4,5,6,7,8] result = [6, 15, 15]

if n = 4

l = [1,2,3,4,5,6,7] result = [10, 18]
Community
  • 1
  • 1
user12345
  • 2,400
  • 8
  • 33
  • 40

6 Answers6

3
n=numConsecutiveElements
[sum(list[x:x+n]) for x in range (0,len(list),n)]

Will do the trick

Description of code

x=0 //Start at the first element
while(x<len(list)): // Until we get to the end of the list
    sum(list[x] + list[x+1] + ... list[x+n-1])  //Sum n elements
    x+=n //Move The first element n elements forward
RussS
  • 16,476
  • 1
  • 34
  • 62
3
def add(seq, n):
    return [sum(seq[i:i + n]) for i in range(0, len(seq), n)]


print(add([1, 2, 3, 4, 5, 6], 3))
print(add([1, 2, 3, 4, 5, 6, 7], 3))
print(add([1, 2, 3, 4, 5, 6, 7, 8], 3))
print(add([1, 2, 3, 4, 5, 6, 7], 4))
Roman Bataev
  • 9,287
  • 2
  • 21
  • 15
1

I think you can do the same thing as before, but just generalize the inputs to izip_longest.

import itertools as it
s = [l[n-i::n] for i in range(n)]
[sum(r) for r in it.izip_longest(*s, fillvalue=0)]

Or in one line

f = lambda n,l: [sum(r) for r in it.izip_longest(*[l[i::n] for i in range(n)], fillvalue=0)]

>>>f(3, range(1,7))
[6,15]
>>>f(3, range(1,8))
[6,15, 7]
>>>f(3, range(1,9))
[6,15,15]
>>>f(4, range(1,8))
[10,18]
Kris Harper
  • 5,672
  • 8
  • 51
  • 96
1

using this reciepe of itertools you could do

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)

[sum(g) for g in grouper(3, l, 0)]
ptitpoulpe
  • 684
  • 4
  • 17
0

Use the grouper recipe:

from itertools import izip_longest

def grouper(n, iterable, fillvalue=None):
    '''grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
From itetools recipes'''
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

def get_n_chunks_summed(it,n):
    return [sum(el) for el in grouper(n, it, 0)]

L = [1,2,3,4,5,6,7]
for n in range(1,5):
    print('{0} -> {1}'.format(n,get_n_chunks_summed(L,n)))

Output:

1 -> [1, 2, 3, 4, 5, 6, 7]
2 -> [3, 7, 11, 7]
3 -> [6, 15, 7]
4 -> [10, 18]
ovgolovin
  • 13,063
  • 6
  • 47
  • 78
0

How about

print map(sum, zip(*[iter(lst + [0] * (len(lst) % n + 1))] * n))
georg
  • 211,518
  • 52
  • 313
  • 390