Reputation: 13
def make_multiplier(scaling_factor):
return lambda x: mul(x, scaling_factor)
def make_exponentiator(exponent):
return lambda x: pow(x, exponent)
mul takes two variables x , y and returns x * y. pow takes two variables x , y and returns x ^ y. Notice that these two functions are quite similar. We could abstract out the commonality into an even more general function make_generator such that we could then just write:
make_multiplier = make_generator(mul)
make_exponentiater = make_generator(pow)
Write the function make_generator.
Test Cases:
make_multiplier(3)(2) = 6
make_exponentiator(3)(2) = 8
My solution:
def make_generator(op):
return lambda x, y: op(x, y)
#################
# DO NOT REMOVE #
#################
def mul(x,y):
return x*y
def pow(x,y):
return x**y
make_multiplier = make_generator(mul)
make_exponentiator = make_generator(pow)
I get the output but I do not pass the given test cases. Any help would be greatly appreciated.
Upvotes: 0
Views: 537
Reputation: 51102
If you have a function like f(x, y)
and you want to be able to call it like g(x)(y)
, that is called currying. You can transform your lambda like this:
# old version
return lambda x, y: op(x, y)
# curried version
return lambda x: lambda y: op(x, y)
Upvotes: 1
Reputation: 21802
Your function is supposed to take an operation and return a function that makes a function to use that operation with a fixed value (Kind of hard to wrap that around your head I know). While your current implementation just returns a function which takes two values and returns the result. Change your implementation as such:
def make_generator(op):
def make_operation(fixed_value):
return lambda x: op(x, fixed_value)
return make_operation
Upvotes: 0