2

First off, sorry about the confusing title but its the only way i could think of describing it. A piece of coursework which i got handed recently asked a question that was to define a function with one argument(x), that returned another function with one parameter(y)which itself would return x*y. We were asked to write this out either using normal functions or lambda's which i opted for lamdas, writing this:

def create_multiplier (x):
   return lambda y: y * x

input1 = int(raw_input("Please enter your initial number for our multiplier"))
multi = create_multiplier(input1)
input2 = int(raw_input("Please enter your second number for our multiplier"))
print input1, " times by ", input2, " = " ,multi(input2)

However i'm now curious how they expected us to achieve it with only functions,initially i thought that maybe you would pass your first number to x in the first function, then pass a number too our second function for y, and because we were returning the second function inside the first, we could use x like a nested variable. That got shot down quick

I understand if you are not willing to reply as this is coursework but this has just got me curious how you were meant to achieve it without presetting our x in a lambda, maybe I'm just looking at it weirdly and its blatantly obvious. Thank you for your replies

4
  • Why are all your sentences run-ons? Commented Oct 6, 2013 at 0:26
  • I'm sorry but never heard that term run-on, could you explain? Commented Oct 6, 2013 at 0:36
  • It's when you write your sentences all connected together like this without commas or anything it's really annoying. Commented Oct 6, 2013 at 0:37
  • Ahh sorry about that, just the way i've got used to writing, will take into consideration next time that my sentences can get a little long winded. Commented Oct 6, 2013 at 0:40

1 Answer 1

4

lambda is just an annoying ;-) shortcut for writing a function (def). So, for example,

def create_multiplier(x):
    def inner_function(y):
        return x*y
    return inner_function

does the same thing.

Later: not quite the same thing. Your lambda actually returns y*x, not x*y ;-)

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

1 Comment

See, this is what i meant by something i should have guessed but was way over analysing stuff,the way they were going on about two functions, one returning the other and so on, kept on attempting to do it by having the two functions defined separately then calling them from each other, should have twigged that they didn't say i could define it inside one another. Thank you very much

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.