-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
4
  • 1
    Yes... replace cubed with lambda x: x**3 and squared with lambda x: x**2?? Commented Aug 11, 2022 at 16:41
  • It certainly can be done. As prev. comment shown. But ... why? Commented Aug 11, 2022 at 16:42
  • It was an interview question. Commented Aug 11, 2022 at 16:57
  • @cvb0rg that's a pretty terrible interview question Commented Aug 11, 2022 at 16:58

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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
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)

Comments

0
squareCubed = lambda x : (x**3)**2

print(squareCubed(2)) # gives 64

1 Comment

This answer was reviewed in the Low Quality Queue. Here are some guidelines for How do I write a good 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.