Function call loops [duplicate] - python

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 2 years ago.
I seem not to be able to understand something fundamental. I have a function A which calls function B and proceeds with the results from it. Function B on the other hand does some iterative calculations and gets called by other functions repeatedly until the iteration is satisfied. When the iteration is satisfied, what I want is one result for function A (from function B), but I seem to get as many results as function B is iteratively called and my code just begins to act silly. It generally gives None result.
Here is what I mean script-wise:
def func_A():
x = 1
y = 1
result_A = func_B(x, y)
print(result_A)
def func_B(x, y):
result_B = x + y
if result_B < 10:
func_C(x,y)
else:
return result_B
def func_C(x, y):
x = x + 1
y = y + 1
func_B(x,y)
func_A()
What I want is func_A call to print 16 when x and y reach 4, however it returns None. I have some complicated nest of functions so I need to solve this problem with this function structure. If anyone could help I would appreciate it very much.

Please see following code.
I added return when call func_C and func_B.
def func_A():
x = 1
y = 1
result_A = func_B(x, y)
print(result_A)
def func_B(x, y):
result_B = x + y
if result_B < 10:
return func_C(x, y)
return result_B
def func_C(x, y):
x = x + 1
y = y + 1
return func_B(x, y)
func_A()

I agree with #Super Star but..
def func_B(x, y):
result_B = x * y #if you want 16 as an answer modify + to *

Related

How to relate a lambda function with a def function in 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.

Function binding in python

n = 7
def f(x):
n = 8
return x + 1
def g(x):
n = 9
def h():
return x + 1
return h
def f(f, x):
return f(x + n)
f = f(g, n)
g = (lambda y: y())(f)
I'm trying to understand and keep track of all the changes in the binding of functions, but cannot seem to grasp why the y parameter in the lambda function gets binded to h() on being called.
The transition from step 14-15 in this Python Tutor link to be precise
Let's change the names of the functions so that twisted code is easier to follow. We can name then sequentially like fun_n and reassign the names after each function definition. I added some comments too
The first one would be
n = 7
def fun_1(x):
n = 8
return x + 1
f = fun1
The second one:
def fun_2(x):
n = 9
def h():
return x + 1
return h
g = fun_2
Now we are ready for some bad renaming
def fun_3(f, x):
return f(x + n)
f = fun_3
And now...
f = f(g, n)
which is equivalent to fun_3(fun2, n) with n=7.
fun_3 will return fun_2(7+n), again with n=7.
fun_2 will return a closure of h with x=14, so it will return a function that returns the result of 14 + 1. So f is now a function that always return 15
Finally,
g = (lambda y: y())(f)
creates a lambda function that calls whatever parameter is passed to it, and calls it passing f as a parameter. It is equivalent to:
fun_4 = lambda y: y()
g = fun_4(f)
I don't think it is really useful as an excercise.

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"]

How to do numerical integration in python?

I can't install anything new I need to use the default python library and I have to integrate a function. I can get the value for any f(x) and I need to integrate from 0 to 6 for my function f(x).
In discrete form, integration is just summation, i.e.
where n is the number of samples. If we let b-a/n be dx (the 'width' of our sample) then we can write this in python as such:
def integrate(f, a, b, dx=0.1):
i = a
s = 0
while i <= b:
s += f(i)*dx
i += dx
return s
Note that we make use of higher-order functions here. Specifically, f is a function that is passed to integrate. a, b are our bounds and dx is 1/10 by default. This allows us to apply our new integration function to any function we wish, like so:
# the linear function, y = x
def linear(x):
return x
integrate(linear, 1, 6) // output: 17.85
# or using lamdba function we can write it directly in the argument
# here is the quadratic function, y=x^2
integrate(lambda x: x**2, 0, 10) // output: 338.35
You can use quadpy (out of my zoo of packages):
import numpy
import quadpy
def f(x):
return numpy.sin(x) - x
val, err = quadpy.quad(f, 0.0, 6.0)
print(val)
-17.96017028290743
def func():
print "F(x) = 2x + 3"
x = int(raw_input('Enter an integer value for x: '))
Fx = 2 * x + 3
return Fx
print func()
using the input function in python, you can randomly enter any number you want and get the function or if hard coding this this necessary you can use a for loop and append the numbers to a list for example
def func2():
print "F(x) = 2x + 3"
x = []
for numbers in range(1,7):
x.append(numbers)
upd = 0
for i in x:
Fx = 2 * x[upd] + 3
upd +=1
print Fx
print func2()
EDIT: if you would like the numbers to start counting from 0 set the first value in range to 0 instead of 1

Why variable defined in a if else blocks can be used outside blocks?

import numpy as np
import tensorflow as tf
class simpleTest(tf.test.TestCase):
def setUp(self):
self.X = np.random.random_sample(size = (2, 3, 2))
def test(self):
a = 4
x = tf.constant(self.X, dtype=tf.float32)
if a % 2 == 0:
y = 2*x
else:
y = 3*x
z = 4*y
with self.test_session():
print y.eval()
print z.eval()
if __name__ == "__main__":
tf.test.main()
Here y is tensorflow variable and is defined inside the if else block, why does it can be used outside the block?
This is more general than tensorflow, it has to do with python's scope of variables. Remember this:
Python does not have a block scope!*
Consider this trivial example:
x = 2
a = 5
if a == 5:
y = 2 * x
else:
y = 3 * x
z = 4 * y
print z # prints 16
What I am trying to say is that y is not a local variable defined in the scope of the body of the if statement, thus it's OK to use it after the if statement.
For more: Variables_and_Scope.
*Block scope in Python

Categories