Is there a way to do the following in just one line with lambdas in python?
squared = lambda x : x**2
cubed = lambda x : x**3
squareCubed = lambda x : squared(cubed(x))
without using any helper functions or reduce.
print(squareCubed(2)) # > 64
Is there a way to do the following in just one line with lambdas in python?
squared = lambda x : x**2
cubed = lambda x : x**3
squareCubed = lambda x : squared(cubed(x))
without using any helper functions or reduce.
print(squareCubed(2)) # > 64
Sure, you can do something like:
squareCube = (lambda f, g: lambda x: f(g(x)))(lambda x: x**2, lambda x: x**3)
But why do this?
In any case, you shouldn't be assigning the result of lambda
to a variable if you are following the official PEP8 style guide. What is wrong with:
def square(x):
return x**2
def cube(x):
return x**3
def compose(f, g):
return lambda x: f(g(x))
square_cube = compose(square, cube)
Is much more readable.
squareCubed = lambda x : (x**3)**2
print(squareCubed(2)) # gives 64
If you want to hard code it:
squareCube = lambda x: (x**3)**2
But generically:
compose = lambda f, g: lambda x: f(g(x))
squareCube = compose(lambda x: x**2, lambda x: x**3)
Or, in one line:
squareCube = (lambda f, g: lambda x: f(g(x)))(lambda x: x**2, lambda x: x**3)