timtommy
timtommy

Reputation: 289

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.

Upvotes: 0

Views: 107

Answers (2)

khelwood
khelwood

Reputation: 59112

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)

Upvotes: 2

umbreon29
umbreon29

Reputation: 233

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

Upvotes: 1

Related Questions