+ 1
Another Lambda question ????
def blondie(f): a = lambda x: f(x +1) return a a = blondie(lambda q: q * q) print(a(2)) //output is 9 I am a bit stuck on the logic
3 Respostas
+ 2
Nice explanation, Tibor Santa . I'd like to add that what we see there is a decorator without using the @... syntax (which you can't on lambda functions). I have added some code for demonstration:
https://code.sololearn.com/cWjO450w8UHs/?ref=app
+ 3
I am trying my best to understand and explain.
Blondie is a "higher order function", meaning that it takes a function as parameter.
It returns the same function (that is enclosed in the lambda expression) but with the functions argument incremented by one.
Then we assign to variable a the result of blondie, that is a function - in this case we passed q*q in a lambda, meaning that blondie gets a square function, and transforms its arguments.
So a() now means (q+1)*(q+1)
Hence in the end, a(2) is rightfully 3*3=9
Hope that makes sense, is a bit convoluted logic for me to actually put this in any real program :)
+ 3
Thoq! Wow, well spotted the decorator paralel. Makes complete sense, just usually decorator / wrapper functions are spelled out more explicitly in the common examples so its hard to notice this is the same thing.