How to relate a lambda function with a def function in Python? - python

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

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 returns function. This feature is used here in both defs. Note that call look as follows
func(x)(x)
func1(3)(1)
as first parts (func(x) and func1(3)) returns functions which are then called with single arguments (x and 1)

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

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.

Related

How do I write this mathematical expression with nested divisions in Python?

I'm having trouble writing this expression for the entry level certification course I'm taking.
Don't use images, instead copy and paste the code.
That question is probably for you to learn how to use parenthesis:
1/(x+1/(x+1/(x + 1/x)))
def foo(x):
return 1 /(x + 1 / (x + 1 / (x + 1.0 / x)))
Looking at this problem strongly suggests recursion to me. I'm not a huge fan of recursion in python, so I would probably implement this as a loop, but I suspect the question is meant for recursion.
How about we define a recursive method like:
def recursive_div(depth, x, y=0):
if depth==1:
return x + 1 / x
return y + 1 / recursive_div(depth-1, x, x)
Then we can do a:
print(recursive_div(4, 2))
We can verify this with one of the other answers:
def foo(x):
return 1.0 /(x + 1.0 / (x + 1.0 / (x + 1.0 / x)))
print(foo(2) == recursive_div(4, 2))

python How to convert the input value into a mathematical function

How to convert an input value into a function!
x = int(input('Enter x value: '))
n = str(input('Enter n value: ')) #n= 2 * x ^ 2 - 2 * x + 2
def f(x,n):
return 2 * x ^ 2 - 2 * x + 2
Actually for what i understand, you don't need to input n.
x = int(input('Enter x value: '))
def f(x):
return 2*x**2 - 2*x+2
n = f(x)
Edit, after rereading others answer yes it probably wanted eval()
Just You can't write "2 * x ^ 2 - 2 * x + 2", the correct way is x**2 instead of x^2
You mean (?):
def f(x, n):
return n*x**2 - 2*x + 2
Or do you mean actually changing the operators?
The question as currently posed is mathematically impossible. You define x & n and are returning a function that you may or may not want to equate to n but its all defined entries.
Still guessing a little at the actual question, but if
y = input("Enter equation to evaluate")
and you expect y to be a quadratic, i.e.:
y = "a*x**b - c*x + d"
then you can get all them from:
import re
y1 = re.split('[* ]',y)
a = y1[0]
b = y1[3] #as there is a null ent between the ** we skip y1[2] and y[1] is 'x'
c = y1[5]
d = y1[8]
If you wanted the operators, then it gets a little harder to follow. So we'll cross that bridge if you do need them.
Or, as the others suggest, just use eval()!!
You could try to use eval.
x=int(input('...'))
n=input('...') # note that input returns a string
def f(x):
global n
return(eval(n))
I think,you are asking .
How to convert an input value into a mathmetical expression ?
If it is so !
use eval()
in python

Making a table in Python 3(beginner)

So I just started learning Python 3 in school, and we had to make a function that
takes a as a parameter, chooses a reasonable value of x, and returns an estimate of the square root of a.
We also had to make a function to test it. We had to write a function named test_square_root that prints a table, where The first column is a number, a; the second column is the square root of a computed with the first function;
the third column is the square root computed by math.sqrt; the fourth column is the absolute value of the difference between the two estimates.
I wrote the first function to find the square root, but I don't know how to make a table like that. I've read other questions on here about tables in Python3 but I still don't know how to apply them to my function.
def mysqrt(a):
for x in range(1,int(1./2*a)):
while True:
y = (x + a/x) / 2
if y == x:
break
x = y
print(x)
print(mysqrt(16))
If you're allowed to use libraries
from tabulate import tabulate
from math import sqrt
def mysqrt(a):
for x in range(1, int(1 / 2 * a)):
while True:
y = (x + a / x) / 2
ifjl y == x:
break
x = y
return x
results = [(x, mysqrt(x), sqrt(x)) for x in range(10, 20)]
print(tabulate(results, headers=["num", "mysqrt", "sqrt"]))
Outputs
num mysqrt sqrt
----- -------- -------
10 3.16228 3.16228
11 3.31662 3.31662
12 3.4641 3.4641
13 3.60555 3.60555
14 3.74166 3.74166
15 3.87298 3.87298
16 4 4
17 4.12311 4.12311
18 4.24264 4.24264
19 4.3589 4.3589
Failing that there's plenty of examples on how to print tabular data (with and without libraries) here: Printing Lists as Tabular Data
def mysqrt(a):
for x in range(1, int(1 / 2 * a)):
while True:
y = (x + a / x) / 2
ifjl y == x:
break
x = y
return x
results = [(x, mysqrt(x), sqrt(x)) for x in range(10, 20)]
print(tabulate(results, headers=["num", "mysqrt", "sqrt"]

Please help me understand an unexpected result when doing arithmetic with functions

How is the answer 1?
Bit confused with this, can someone explain why for beta y - x is 2 - 3 rather than 3 - 2?
What does alpha(2, 3) evaluate to:
def alpha(x, y):
return x + beta(y, x)
def beta(x, y):
return y - x # [1]
alpha(2,3)
results in the following code being executed:
return 2 + beta(3,2) # (*)
The beta(3,2) call in turn results in:
return 2 - 3
which gives -1, so in (*) you have 2 + -1, which is 1.
You are getting confused by the names in alpha; it calls beta() with the arguments swapped.
Pay close attention to the x and y in alpha(). If it helps, replace the arguments with longer names:
def alpha(first, second):
return first + beta(second, first)
Filling in the values everywhere gives you:
alpha(2, 3)
-> 2 + beta(3, 2)
-> 2 + (2 - 3)
-> 2 + -1
-> 1
Alpha evaluates:
x-beta(y,x)=x+x-y=2*x-y.
Mind you swapped the parameters of beta in the call.
The function arguments swap places:
return x + beta(y, x) <-- y, x
def beta(x, y): <-- x, y
So function call beta(2,3) executes return 2 - 3
You are passing y as x and x as y.
In that case alpha(2, 3) means 2 + beta(3, 2) which evaluates to 2 + 2 - 3 which is 1.
alpha(2,3)
-> 2+beta(3,2)
-> 2+(2-3)
-> 2+2-3 = 4-3 = 1

Could anyone show me how the recursive part of this function works?

I've been given an example of a recursive function and I just need some help understanding it.
I know that recursive functions a) must have a base case, b) must change the arguments and move towards the base case and c) must call itself
The code is below:
def func(x,y):
if y == 0:
return 0
else:
return x + func(x,y-1)
I'm just struggling to understand the func(x,y-1). I know the function returns the product of x and y but I'm not sure how the recursive part of the function works.
your function decrease the value of y every times till it got 0 then in every call you remain a x so depend on the value of y you have the sum of x actually the function is y*x
>>> def func(x,y):
... if y == 0:
... return 0
... else:
... return x + func(x,y-1)
...
>>> func(3,4)
12
>>> func(3,0)
0
for example for func(3,4) your function return this :
3 + func(3,3)= 3+ func(3,2) = 3 + func(3,1) = 3 + func(3,0)= 3+0
if we replace the funcs , we would have : 3+(3+(3+(3+0))) that is equal 12 .
This function is adding x element y times. So here's how it works:
When you call your func with 3, 2, you do the following:
you check if y is 0, if its 0 return 0. This is needed condition to return from recursion.
If its not zero, you do add 3 + fun(3, 1) This part goes to stack and it calls function again.
Again it checks y value and does 3 + func(3, 0). This part again goes to stack and calls function again
Now its 0, so it returns and pop's top elemnt from stack i.e. 3 + fun(3, 0) and now since fun(3, 0) returned 0 it will return 3
Again pop top element which we left i.e. 3 + fun(3, 1). fun(3,1) in previous step returned 3, so it will replace fun(3, 1) with 3 and return 3 + 3 = 6.
-Now since you dont have any element on stack (i.e. no more function evaluation left), it returns 6 and returns back to the caller.
func(x,y-1) simply calls func again with new values x & y-1
For example,
take x=5, y=6
first call will be: func(5,6)
after that, It'll call func(5,5) -> func(5,4) -> func(5,3) -> func(5,2) -> func(5,1) -> func(5,0)
at last func(5,0) will return 0 to its caller.
& It'll go all the way up to the first call...
In short, every time that function recurs, It calls Itself with one less value of y (i.e. second variable) & eventually It'll terminate when y=0.
We'll assume that func is a function which returns the product of its two arguments (assuming y is a non-negative integer). It's clearly true when y is 0, because
if y == 0:
return 0
and x * 0 is 0 for any value of x. Otherwise, it returns
x + func(x, y-1), and since we are assuming that func(x, y-1) returns the product of x and y-1, we can confirm that
x + x*(y-1) = x + x*y - x
= x*y
so func(x, y) indeed returns x * y for any x and any non-negative integer y.
My college professor use to tell us to "trust your recursion". When making recursive calls, simply assume that it the recursive call will return "the right thing" when writing the recursive case; as long as you are properly making the recursive call "simpler" than the original call, it will "just work".
I should also say that the following optimization should be done: if y == 0 or x == 0:, or a call to func(0, 1000) would needlessly put values in the stack
As you said, the function keeps calling itself. If it had been like this:
def func(x,y):
return func(x,y)
it would endlessly call itself and wouldn't give you a result.
However if you make y smaller with every call, you can stop the "madness" at some point, e.g. when y reaches zero. Then if y is 1 smaller every time, func(2, 2) would call func(2, 1) which would call func(2, 0) which would finally return a value because by then y=0. func(2, 1) uses that value and adds "x" to it, and so on. Finally func(2, 2) would add x to that return value. The return is then x times y function calls or 2*2.
Structure and Interpretation of Computer Programs (SICP) describes an iterative process as one which "carries with it" all the information needed to solve the problem, while a recursive process has to "remember where it came from" in order to solve the problem.
One way to see the distinction is to trace how the length of the problem grows and then shrinks as it is being solved.
def func(x,y):
if y == 0:
return 0
else:
return x + func(x,y-1)
func(5,4)
func(5,4) --> 5 + func(5,3)
func(5,4) --> 5 + func(5,3) --> 5 + func(f,2)
func(5,4) --> 5 + func(5,3) --> 5 + func(f,2) -- > 5 + func(5,1)
func(5,4) --> 5 + func(5,3) --> 5 + func(f,2) -- > 5 + func(5,1) --> 5 + func(5,0)
func(5,4) --> 5 + func(5,3) --> 5 + func(f,2) -- > 5 + func(5,1) --> 5 + func(5,0) --> 0
func(5,4) --> 5 + func(5,3) --> 5 + func(f,2) -- > 5 + func(5,1) --> 5 + 0
func(5,4) --> 5 + func(5,3) --> 5 + func(f,2) -- > 5 + 5
func(5,4) --> 5 + func(5,3) --> 5 + 5 + 5
func(5,4) --> 5 + 5 + 5 + 5
5 + 5 + 5 + 5
20

Categories