Skip to main content

Using Python 2

1 Using Python 2

1.Ninja way:

1.1 Ninja way

Is fun and good for learning python, but don't go for it in production code

from operator import iadd l = [4,2,1,3] reduce(lambda result, x: iadd(result, [result[-1] + x]), l, [0])[1:] 

2.Explicit way

1.2 Explicit way

I will just copy @Grapier solution for this because I would do the same:

def add_one_by_one_gen(l): cumsum = 0 for elt in l: cumsum += elt yield cumsum 

Using Python 3

2 Using Python 3

from itertools import accumulate accumulate(l) 

Using Python 2

1.Ninja way:

Is fun and good for learning python, but don't go for it in production code

from operator import iadd l = [4,2,1,3] reduce(lambda result, x: iadd(result, [result[-1] + x]), l, [0])[1:] 

2.Explicit way

I will just copy @Grapier solution for this because I would do the same:

def add_one_by_one_gen(l): cumsum = 0 for elt in l: cumsum += elt yield cumsum 

Using Python 3

from itertools import accumulate accumulate(l) 

1 Using Python 2

1.1 Ninja way

Is fun and good for learning python, but don't go for it in production code

from operator import iadd l = [4,2,1,3] reduce(lambda result, x: iadd(result, [result[-1] + x]), l, [0])[1:] 

1.2 Explicit way

I will just copy @Grapier solution for this because I would do the same:

def add_one_by_one_gen(l): cumsum = 0 for elt in l: cumsum += elt yield cumsum 

2 Using Python 3

from itertools import accumulate accumulate(l) 
Source Link
Alex
  • 1.7k
  • 8
  • 12

Using Python 2

1.Ninja way:

Is fun and good for learning python, but don't go for it in production code

from operator import iadd l = [4,2,1,3] reduce(lambda result, x: iadd(result, [result[-1] + x]), l, [0])[1:] 

2.Explicit way

I will just copy @Grapier solution for this because I would do the same:

def add_one_by_one_gen(l): cumsum = 0 for elt in l: cumsum += elt yield cumsum 

Using Python 3

from itertools import accumulate accumulate(l)