How to translate this generator function to lambda expression

python generator expression
python generator to list
def f(nums):
    sum = 0
    for i in nums:
        sum += i
        yield sum

I was trying to initiate a new list which every index's value is previous accumulation, according to args nums(type list), using list comprehension.

the final result would look like[i for i in f(nums)]

Is there ways to translate the function to lambda expression? or any other ones to make it one-line?


I would propose the following as a replacement for that:

nums=[1,2,3,4]
gen=(sum(li[0:i]) for i,_ in enumerate(li,1))

That is a generator, so a O(n^2) operation is not being performed for elements not yet needed.

Then to get the elements, use next:

>>> next(gen)
1
>>> next(gen)
3
>>> next(gen)
6
>>> next(gen)
10

And if you do want them all at once, just use list on the generator:

>>> gen=(reduce(add, li[0:i]) for i,_ in enumerate(li,1))
>>> list(gen)
[1, 3, 6, 10]]

The performance of this function on non trivial lists is HORRIBLE because it has O(n^2) complexity. Only use it as a curiosity. See timings below.


And (thanks to AChampion) another reduce:

>>> reduce(lambda x, y: x+[y+next(iter(x[-1:]), 0)], nums, [])
[1, 3, 6, 10]

But the right answer is itertools.accumulate or your your original function. Any one line solution will have far greater computational complexity.


Here is a set of timings to show that other than itertools.accumulate, the single line replacements have O(n^2) type complexity (ie, 10x more items, 100x more time roughly). That is because for each element in the list, because lambdas or reduce or comprehensions do not have any form of accumulator, the entire list up to that point must be looped over again. Your original function and itertools.accumulate are both O(n) type complexity (ie, 10x more items, a linear 10x more time).

Here is a graph and cheatsheet of O Complexity.

Here is the timing and results:

from itertools import accumulate
from functools import reduce 

def f1(nums):
    sum_ = 0
    for i in nums:
        sum_ += i
        yield sum_

def f2(nums):
    return (sum(nums[0:i]) for i,_ in enumerate(nums,1))

def f3(nums):
    return  accumulate(nums)

def f4(nums):
    return reduce(lambda x, y: x+[y+next(iter(x[-1:]), 0)], nums, [])

if __name__=='__main__':
    import timeit    
    for case, x in (('small',100),('med',1000),('large',10000),('huge',100000)):  
        data=list(range(x))
        print("Case {}, {:,} x, All equal: {}".format(case,x,(list(f1(data))==list(f2(data))==list(f3(data))==list(f4(data)))))
        for f in (f1,f2,f3,f4):
            print("   {:^10s}{:.4f} secs".format(f.__name__, timeit.timeit("list(f(data))", setup="from __main__ import f, data", number=10)))

Results:

Case small, 100 x, All equal: True
       f1    0.0001 secs
       f2    0.0007 secs
       f3    0.0000 secs
       f4    0.0006 secs
Case med, 1,000 x, All equal: True
       f1    0.0007 secs
       f2    0.0424 secs
       f3    0.0003 secs
       f4    0.0139 secs
Case large, 10,000 x, All equal: True
       f1    0.0083 secs
       f2    3.9526 secs
       f3    0.0036 secs
       f4    1.2756 secs
Case huge, 100,000 x, All equal: True
       f1    0.0977 secs
       f2    427.4129 secs
       f3    0.0532 secs
       f4    159.2506 secs

Translation of Lambda Expressions, Functional interfaces are a central aspect of lambda expressions in Java. A functional interface is an interface that has one non- Object method, such as Runnable  The Lambda expression used in the example is short and quick and does not really expose the power of the map function. Lets say instead you have a dataset that holds a set of waves and you want to run a routine you wrote to smooth out all the waves - this would work well for that.


This is one way to do it:

nums=[1,2,3,4]

[sum(nums[:idx+1]) for idx, i in enumerate(nums)]

Output:

[1, 3, 6, 10]

Another way is to use itertools.accumulate as suggested by @Blckknght.

from itertools import accumulate

list(accumulate(nums))

Output:

[1, 3, 6, 10]

How to Use Python Lambda Functions – Real Python, Lambda expressions in Python and other programming languages have their lambda calculus and Turing machines, can be translated into each another. and lambda with list comprehensions or generator expressions. The simplest form of lambda expression to translate is one that captures no state from its enclosing scope (a stateless lambda): class A { public void foo() { List<String> list = list.forEach( s -> { System.out.println(s); } ); } }


If the list is continuously.

A simple but not efficient way:

[sum(range(1, i+1)) for i in range(1, 5))]

Output:

[1, 3, 6, 10]

Lambda Expressions, Lambda Expressions are ideally used when we have something simple to be done an Lambda expressions also known as anonymous functions. Python Complex Numbers · Python Containers · Converting Integer to String in Python NOTE: in Python 3 built in function return generator objects, so you have to call list  A Python lambda function behaves like a normal function in regard to arguments. Therefore, a lambda parameter can be initialized with a default value: the parameter n takes the outer n as a default value. The Python lambda function could have been written as lambda x=n: print(x) and have the same result.


Functional Programming HOWTO, Generator expressions return an iterator that computes the values as necessary, not needing to Convert the lambda to a def statement, using that name. To create a lambda expression, you specify input parameters (if any) on the left side of the lambda operator and an expression or a statement block on the other side. Any lambda expression can be converted to a delegate type. The delegate type to which a lambda expression can be converted is defined by the types of its parameters and return value.


6. Expressions, The yield expression is used when defining a generator function or an Instead, convert to a floating point number using the abs() function if appropriate. The expression lambda parameters: expression yields a function object. Simple generators can be easily created on the fly using generator expressions. It makes building generators easy. Similar to the lambda functions which create anonymous functions, generator expressions create anonymous generator functions. The syntax for generator expression is similar to that of a list comprehension in Python. But the square brackets are replaced with round parentheses.


Compiler Generators: What They Can Do, What They Might Do, and , intermediate lambda expression is translated into so-called SECD-code (see are implemented by functions which construct and decompose lists (like CAR,  Translate a special character in a character vector using the regexptranslate function. Then use the result as a regular expression in regexp. Create a character vector that contains the characters ' '. chr = 'The sequence generates a new line.'.