Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I remove double evaluation whilst keeping lambda expression

def bar(x):
    # some expensive calculation
    <snip>

foo = lambda(x): bar(x) if bar(x) > 10 else 0

However here I have calculated foo twice. Is there a way to still write this as a one liner but avoid the double evaluation. I tried

foo = lambda(x): v if (v = bar(x)) > 10 else 0

but that doesn't work.

like image 553
bradgonesurfing Avatar asked Mar 04 '23 07:03

bradgonesurfing


1 Answers

Preevaluate:

foo    = lambda(x): x if x > 10 else 0
result = foo(bar(x))

Here you can see what is the similarities to your code:

lambda (x): foo(x) if foo(x) > 10 else 0 == (lambda(x): x if x > 10 else 0)(foo(x))

What you seek is not possible unless you create some kind of mutable state object or some other weird trick.

@Alakazam answer is tricky and smart, use it on your own risk. It can be better using iterators and next to avoid extra intermediate list:

lambda x: next(res if res > 10 else 0 for res in (bar(x), ))

Here you have the live example

like image 193
Netwave Avatar answered Apr 24 '23 22:04

Netwave