Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum consecutive numbers in a list. Python

i'm trying to sum consecutive numbers in a list while keeping the first one the same.

so in this case 5 would stay 5, 10 would be 10 + 5 (15), and 15 would be 15 + 10 + 5 (30)

x = [5,10,15]
y = []

for value in x:
   y.append(...)

print y

[5,15,30]
like image 420
O.rka Avatar asked Jun 12 '13 20:06

O.rka


People also ask

How do you find the sum of consecutive numbers in a list Python?

Consecutive Numbers Formula The formula for adding 'n' consecutive numbers = [a + (a + 1) + (a + 2) + . {a + (n-1)}]. So, the sum of 'n' consecutive numbers or sum of 'n' terms of AP (Arithmetic Progression) = (n/2) × (first number + last number). Even Consecutive Numbers Formula = 2n, 2n+2, 2n+4, 2n+6,…

How do you do consecutive sums in Python?

You must do or base = base + 1 or bas += 1 not both otherwise you sum base + (base + 1) that is wrong.

How do you sum all numbers in a list in Python?

Python provides an inbuilt function sum() which sums up the numbers in the list. Syntax: sum(iterable, start) iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers.

How do you find the sum of consecutive numbers?

Using the Formula(n / 2)(first number + last number) = sum, where n is the number of integers.


2 Answers

You want itertools.accumulate() (added in Python 3.2). Nothing extra needed, already implemented for you.

In earlier versions of Python where this doesn't exist, you can use the pure python implementation given:

def accumulate(iterable, func=operator.add):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = next(it)
    yield total
    for element in it:
        total = func(total, element)
        yield total

This will work perfectly with any iterable, lazily and efficiently. The itertools implementation is implemented at a lower level, and therefore even faster.

If you want it as a list, then naturally just use the list() built-in: list(accumulate(x)).

like image 108
Gareth Latty Avatar answered Nov 08 '22 09:11

Gareth Latty


y = [sum(x[:i+1]) for i in range(len(x))]
like image 43
Brent Washburne Avatar answered Nov 08 '22 10:11

Brent Washburne