Python function - why is it called twice? - python-3.x

In the following Code the function g() is called twice, but why? Is it because in function f() that x=g and than function x() is called but in fact it is g()?
x = 99
def f():
x = g
x()
x = 17
def g():
global x
x = 14
g()
f()

You can also check this by simply adding a print statement as in the following:
x = 99
def f():
x = g
print(x)
x()
x = 17
def g():
global x
x = 14
g()
f()
Output would be: <function g at 0x7f2147265c80> which shows that printing x in line 4 is indeed calling the function g()

Related

How to use scipy's fminbound function when function returns a dictionary

I have simple function for which I want to calculate the minimum value
from scipy import optimize
def f(x):
return x**2
optimize.fminbound(f, -1, 2)
This works fine. Now I modify above function which now returns a dictionary
def f1(x):
y = x ** 2
return_list = {}
return_list['x'] = x
return_list['y'] = y
return return_list
While it is returning multiple objects x and y, I want to apply fminbound only on y, the other object x is just for informational purpose for other use of this function.
How can I use fminbound for this setup?
You need a simple wrapper function that extracts y:
def f1(x):
y = x ** 2
return_list = {}
return_list['x'] = x
return_list['y'] = y
return return_list
optimize.fminbound(lambda x: f1(x)['y'], -1, 2)

How do I return a value from a higher-order function?

guys how can I make it so that calling make_repeater(square, 0)(5) return 5 instead of 25? I'm guessing I would need to change the line "function_successor = h" because then I'm just getting square(5) but not sure what I need to change it to...
square = lambda x: x * x
def compose1(h, g):
"""Return a function f, such that f(x) = h(g(x))."""
def f(x):
return h(g(x))
return f
def make_repeater(h, n):
iterations = 1
function_successor = h
while iterations < n:
function_successor = compose1(h, function_successor)
iterations += 1
return function_successor
it needs to satisfy a bunch of other requirements like:
make_repeater(square, 2)(5) = square(square(5)) = 625
make_repeater(square, 4)(5) = square(square(square(square(5)))) = 152587890625
To achieve that, you have to use the identity function (f(x) = x) as the initial value for function_successor:
def compose1(h, g):
"""Return a function f, such that f(x) = h(g(x))."""
def f(x):
return h(g(x))
return f
IDENTITY_FUNCTION = lambda x: x
def make_repeater(function, n):
function_successor = IDENTITY_FUNCTION
# simplified loop
for i in range(n):
function_successor = compose1(function, function_successor)
return function_successor
if __name__ == "__main__":
square = lambda x: x * x
print(make_repeater(square, 0)(5))
print(make_repeater(square, 2)(5))
print(make_repeater(square, 4)(5))
and the output is
5
625
152587890625
This isn't most optimal for performance though since the identity function (which doesn't do anything useful) is always part of the composed function, so an optimized version would look like this:
def make_repeater(function, n):
if n <= 0:
return IDENTITY_FUNCTION
function_successor = function
for i in range(n - 1):
function_successor = compose1(function, function_successor)
return function_successor

Closures in Python - executing an inner function?

Why is this in Python3 executing the inner function?
def outer():
out_var = 1
def inner():
inn_var = 2
res = out_var + inn_var
print(res)
return inner
x = outer()
y = outer()
The output is
3
3
Shouldn't it the inner func be executed and the result printed only when executing x() and y()?

Perplexed over a simple function in Python

Look at the code below:
def foo (x):
print("foo environment: x = {0}".format(x))
def bar (z, x = 0):
print("bar environment: z = {0} and x = {1}. Value to be returned: {2}".format(z, x, x+z))
return z + x
return bar(3)
foo(5)
foo environment: x = 5
bar environment: z = 3 and x = 0. Value to be returned: 3
3
Since in the foo environment x = 5, why bar uses the value 0?
You are only passing one argument here:
return bar(3)
The bar function accepts two values, one z and one x (x has a default value (0) and that is why only 1 argument is enough). By only passing the z, x=0.
Try this, and see what happens:
return bar(3, x)

Accessing global variable in function in python

I have two pieces of code:
def g(y):
print(x)
x = 5
g(x)
and
def h(y):
x = x + 1
x = 5
h(x)
The first piece of code works perfectly fine printing '5' while the second piece returns:
UnboundLocalError: local variable 'x' referenced before assignment
What does this actually mean? Is it trying to say that it tried to evaluate the line x = x + 1 before it evaluates the line x=5? If that is so, why has the first piece of code not generated any error? It similarly had to evaluate the line print(x) before x was assigned a value.
I think I might have an misunderstanding how functions are called. But I do not know what it is that I got wrong.
# first block: read of global variable.
def g(y):
print(x)
x = 5
g(x)
# second block: create new variable `x` (not global) and trying to assign new value to it based on on this new var that is not yet initialized.
def h(y):
x = x + 1
x = 5
h(x)
If you want to use global you need to specify that explicitly with global keyword:
def h(y):
global x
x = x + 1
x = 5
h(x)
Just as Aiven said, or you can modify the code like this:
def h(y):
x = 9
x = x + 1
print(x) #local x
x = 5
h(x)
print(x) #global x

Resources