-1

I have difficulty understanding how should I solve the following problem.

I would like to sum every "n" elements in a list in the consecutive order. For example:

n = 2
seq = [2, 2, 1, 3]
res = [4, 3, 4]

How can I apply certain condition (such as a sum) on every n elements of a list? I do not want to import any special libraries because it will help me to understand the basics.

redacted
  • 3,789
  • 6
  • 25
  • 38
may
  • 1,073
  • 4
  • 14
  • 31

4 Answers4

2

Use a while loop to iterate through the list. First create a variable i, which is 1 less than the n, then go through the while loop, incremented i while it is less than len(seq) (which in this case is 4). Each time, add the item at the current index (i) in the list and the preceding n items.

n = 2
seq = [2, 2, 1, 3]
res = []

i = n-1

while i < len(seq):
    res.append(sum(seq[i - (n-1):i+1]))
    i += 1

Then print(res) will output [4, 3, 4].

Ollie
  • 1,641
  • 1
  • 13
  • 31
1

Here is one way using map and zip:

In [9]: def summer(seq, le):
   ...:     return map(sum, zip(*[seq[i:] for i in range(le)]))
   ...: 

In [10]: 

In [10]: list(summer(seq, 2))
Out[10]: [4, 3, 4]

In [11]: list(summer(seq, 3))
Out[11]: [5, 6]
Mazdak
  • 105,000
  • 18
  • 159
  • 188
1

There are very many ways to produce a sliding window sum. For instance:

winsize = 2
inputs = [2, 2, 1, 3]

method1 = [sum(inputs[start:start+winsize])
           for start in range(0, len(inputs)-winsize+1)]

method2 = []
accumulator = 0
for i,v in enumerate(inputs):
    accumulator += v
    if i >= winsize:
        accumulator -= inputs[i-winsize]
    if i >= winsize-1:
        method2.append(accumulator)
Yann Vernier
  • 15,414
  • 2
  • 28
  • 26
0
>>> n = 2
>>> seq = [2, 2, 1, 3]
>>> res = []
>>> for i in range(len(seq) - n + 1):
...     res.append(sum(seq[i:i+n]))
... 
>>> res
[4, 3, 4]

This does the work - just loop through the elements upto len(seq) - n + 1 - this is because you don't want python to sum the last numbers which are less than n in length.

thelogicalkoan
  • 620
  • 1
  • 5
  • 13