Trying to set function as parameter - python

I'm trying to create function that get a number and return function. For example:
>>> const_function(2)(2)
2
>>> const_function(4)(2)
4
How can I return function as output? I've tried to write this:
def const_function(c):
def helper(x):
return c
return helper(x)
Why is this not working?

You're returning the result of calling the function. If you want to return the function itself, simply refer to it without calling it:
def const_function(c):
def helper(x):
return c
return helper # don't call it
Now you can use it with the desired results:
>>> const_function(2)
<function const_function.<locals>.helper at 0x0000000002B38D90>
>>> const_function(2)(2)
2
>>> const_function(4)(2)
4

Try:
return helper
When you do:
return helper(x)
it calculates the result of helper(x) and returns it. When you return helper it will return the function itself.

Related

Lambda Function: Understanding lambda function?

CASE 1: ERROR output
def myfunc(n):
return lambda a : a * n
mytripler(11) = myfunc(3) => Error
===========================================
CASE 2: Correct output
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
How does the value 11 get passed to the method in the second case?
When myfunc is executed it is returning another function...
def myfunc(n):
Return lambda x : x*n
Is same as writing..
def myfunc(n):
def f(x):
Return x*n
return f
Hence in first function you are returning another function and as it has formed closure it has access to n variable of parent function.
It is because of the way lambda functions work, the value 11 is used in place of the variable 'a' in your case and n is already 3.
When mytripler = myfunc(3) is ran, it is returning a function(lambda) which looks like
def fun(a) :
return a * 3
Now the mytripler points to the above function "fun" which takes a single argument and multiplies it by 3.
Your function myfunc returns a function/callable (in this case lambda function), as can be seen here:
>>> def myfunc(n):
... return lambda a : a * n
>>> print(myfunc)
<function myfunc at 0x7efe15c9dea0>
Now, when we make the call to myfunc, the value passed as n will be bound in the lambda function:
>>> mytripler = myfunc(3)
>>> print(mytripler)
<function myfunc.<locals>.<lambda> at 0x7efe14f20598>
At this point mytripler is defined as lambda a : a * 3; the n was replaced by the value (or also: has been assgined the value) that we passed as argument to myfunc(). Note that this lambda construct is functionally equivalent to:
>>> def mytripler(a):
... return a * 3
Now, we can call mytripler with an value to make the final calculation/execution:
>>> mytripler(11)
33
Your error is that you cannot assign a value to a function call on the left-hand side:
>>> mytripler(11) = myfunc(3)
File "<input>", line 1
SyntaxError: can't assign to function call
But you can skip the intermediary step of assigning the result of myfunc to the name mytripler, and instead do both function calls chained together, like this:
>>> myfunc(3)(11)
33
Does that answer your question?

Is there a way to have a lambda reference inside a function always return the opposite bool value?

If I have a function that takes in a lambda reference as a parameter, and returns that reference so when it's called, it returns the value of that lambda function (boolean).
Is there a way to have it return the opposite boolean value?
def returns_diff(lambda_function):
return lambda_function
f = returns_diff(lambda x : x > 2)
f(0)
# I know I can do it this way but I want to do it inside the function.
# print(not(f(0)))
---> Should return True because it's supposed to return False since 0 is not bigger than two (return the opposite value of the lambda function)
I know I can just do: not(f(0)) when calling it, but I want to do it inside the function, not when I call it.
If you want to generate a function that returns the boolean opposite of a given function, you can do it like this:
def returns_diff(func):
return lambda x: not func(x)
f = returns_diff(lambda x: x>2)
f(0) # returns True
That's assuming the functions take one argument, as in your question. You can also make a version that works for functions with any number of positional or keyword arguments:
def returns_diff(func):
return lambda *args, **kwargs: not func(*args, **kwargs)
Can i use classes? Or it need to be just plain functions? With classes i would do
class diff:
def __init__(self,lambda_func):
self.lambda_func = lambda_func
def __call__(self,x):
return not(self.lambda_func(x))
f = diff(lambda x: x > 2)
f(0) #True

What is the syntax for the input for a def function with multiple nested functions?

I'm learning Python right now and I am just trying to get to grips with all of the syntax options.
Currently, the only thing that I can't seem to google up is what to do if I for some reason want to define a function which contains multiple other defines.
While I understand what to do if there's only 1 define inside the the larger define (val = f()(3,4) returns 7 if you exclude the second def below), I don't know how to correctly use the function below.
If it's possible, what is the syntax for a def function with an arbitrary amount of defined functions within it?
Code:
def f():
def x(a,b):
return a + b
return x
def y(c,d):
return c + d
return y
val = f()(3,4)(5,6)
print(val)
I expected the above to return either (7,11) or 11. However, it returns 'int object is not callable'
When you write val = f()(3,4)(5,6), you want f to return a function that also returns a function; compare with the simpler multi-line call:
t1 = f()
t2 = t1(3,4)
val = t2(5,6)
The function f defines and returns also has to define and return a function that can be called with 2 arguments. So, as #jonrsharpe said, you need more nesting:
def f():
def x(a, b):
def y(c, d):
return c + d
return y
return x
Now, f() produces the function named x, and f()(3,4) produces the function named y (ignoring its arguments 3 and 4 in the process), and f()(3,4)(5,6) evaluates (ultimately) to 5 + 6.

build function signature from list of variable names

I have a list of variable names:
var_names = ['x','y']
and a function that takes vector input, e.g.
def f(vec):
return vec[0]+vec[1]
I want to build a function that creates a multi-input function that does the same thing as f, e.g.
def g(x,y):
return f([x,y])
Does anybody know how to create a function like g in an automated way? I tried this
def _create_multiInput_fcn(vector_fcn,var_list):
def g(*var_list):
out = vector_fcn(var_list)
return out
return g
g = _create_multiInput_fcn(f,var_list)
but that just gave me something with a signature like this:
<function __main__._create_multiInput_fcn.<locals>.f(*var_list)>
when I really want this:
<function __main__._create_multiInput_fcn.<locals>.f(x,y)>
I appreciate any help/advice that someone can give me. Thanks.
You can use the built-in function exec to define a function dynamically:
def _create_multiInput_fcn(vector_fcn,var_list):
exec('''
def g({0}):
return vector_fcn([{0}])
'''.format(','.join(var_list)), globals(), locals())
return g
g = _create_multiInput_fcn(f,var_list)

Pass only one variable to a function in Python

Let's say I have the function
def f(x,y):
return x+y
and I want to create a function that returns a function in which a specific variable is passed:
def G(f,n,q): #a function in which the n-th variable of function f is passed the value q
return ??
The question is: how should I define G?
For example, G(f,0,1) should return the function f in which variable 0 is passed the value one. In other words, G(f,0,1) should behave as g, which I define by
def g(x):
return f(1,x)
In that case you can construct a function that construct a function. Like:
def G(f,n,q):
def h(*args):
ls = list(args)
ls.insert(n,q)
return f(*ls)
return h
You thus construct a function h that takes as input an arbitrary number of elements *args. Then you convert it to a list(..) such that you can alter the list. Next you insert the given parameter q as index n into the list, and you pass that list with an asterisk to the given function f.
Here's a smaller, simpler, related working example. In general, you might want to read about python decorators and partial functions.
>>> def power(x):
... def foo(y):
... return y**x
... return foo
...
>>> square = power(2)
>>> cube = power(3)
>>> square(2)
4
>>> square(3)
9
>>> cube(2)
8
>>> cube(3)
27
>>>
You can take a look at the functools module.
For example, using the partial method you can do:
from functools import partial
def G(f, n, q):
return partial(f, n=q)
This replaces the keyword argument named n withq
You could also replace positional arguments but they have to be in order:
from functools import partial
def G(f, n, q):
return partial(f, q)
This replaces the first argument with q

Categories

Resources