I just enrolled to a Data Science training course. In the pre-work for Data Science, there is some "basic" python stuff and I am learning the def functions, as well as the lambda functions.
Below you can find a combination of both, but I have no idea how it actually works and what is the process flow.
The code I do not understand how it works is the following:
def func(x):
return lambda y: (x y 1)
def func1(x):
return lambda y : (func(x)(x) y 1)
print(func1(3)(1))
And the returned value is:
9
CodePudding user response:
def func(x):
return lambda y: (x y 1)
def func1(x):
return lambda y : (func(x)(x) y 1)
print(func1(3)(1))
Functions in python
are 1st class citizens, therefore you might create functions which return
s function. This feature is used here in both def
s. Note that call look as follows
func(x)(x)
func1(3)(1)
as first parts (func(x)
and func1(3)
) return
s functions which are then called with single arguments (x
and 1
)
CodePudding user response:
This is purposefully convoluted code and you will not see such a code in real life. And if you do, then run away from that company or project as fast as you can. And regarding to your understanding, try to expand the function calls the same way as you expand mathematical formulas. If you understand what lambda is, then it should be easy to expand this step by step.
So we want to evaluate this func1(3)(1)
. Lets dig into it step by step.
Step1: Lets' start with the first part:
func1(3)
==> lambda y: (func(x)(x) y 1)
where x
is 3
==> lambda y: (func(3)(3) y 1)
Step2: Let's have a look at this part:
func(3)
==> lambda y: (x y 1)
where x
is 3
==> lambda y: (3 y 1)
Step3: Now let's go one step further:
func(3)(3)
==> (3 y 1)
where y
is 3
==> 3 3 1
==> 7
Step 4: now let's get back to the result from step 1:
lambda y: (func(3)(3) y 1)
==> lambda y: (7 y 1)
Step 5: and now lets put this all together:
func1(3)(1)
==> (7 y 1)
where y
is 1
==> 9
CodePudding user response:
i will try my best.
im experimenting with the code and do something with the first function it will look like this :
def func(x):
return lambda y: (x y 1)
print(func(3)(1))
the interesting part is you actually can put the lambda value beside the the function value so lambda value will be 1 and function value will be 3 then the result would be:
3 1 1 = 5
now the hard part that take me long to quite understand it because its tricky.
def func(x):
return lambda y: (x y 2)
print(func(3)(1))
def func1(x):
return lambda y : (func(x)(x) y 1)
print(func1(4)(1))
i see something tricky in this code, like:
4 4 1 1 = 10
like where is the other value to get the number to be 12 and that is where it get the value from the above function that is 2 to be putted in the function and the result would be:
4 4 1 1 2 = 12
that's what i know.
now my brain is hot.