-2

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
cvb0rg
  • 73
  • 6

3 Answers3

1

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.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • Thanks this makes sense. I'm a bit confused as to how in ```var = () ()``` the first parentheses know to look in the 2nd () for the definitions of f and g? – cvb0rg Aug 11 '22 at 16:50
  • 1
    The first parentheses just groups `(lambda f, g: lambda x: f(g(x)))(lambda x: x**2, lambda x: x**3)`, this results in a function (of course - it is a lambda expression), you then **call** that function, passing it the corresponding arguments. It's exactly like the more readable version I showed below it – juanpa.arrivillaga Aug 11 '22 at 16:57
0
squareCubed = lambda x : (x**3)**2

print(squareCubed(2)) # gives 64
JasonF
  • 1
  • 2
  • This answer was reviewed in the [Low Quality Queue](https://stackoverflow.com/help/review-low-quality). Here are some guidelines for [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). Code only answers are **not considered good answers**, and are likely to be downvoted and/or deleted because they are **less useful** to a community of learners. It's only obvious to you. Explain what it does, and how it's different / **better** than existing answers. [From Review](https://stackoverflow.com/review/low-quality-posts/32465195) – Trenton McKinney Aug 11 '22 at 17:39
0

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)
The Thonnu
  • 3,578
  • 2
  • 8
  • 30