Lambda functions in Python
Here is a very simple lambda function, this example is one of creating a polynomial function with given coefficients, and storing that as a lambda function in a variable 'f' that can now be used as a function, cool!
# This returns a function that represents a polynomial
# Input is a dictionary with a,b,c being required keys
def polyf(**coeffs):
"""Returns a lambda function"""
return lambda x: coeffs['a']*x*x + coeffs['b']*x+coeffs['c']
# now returns a lambda function that will evaluate 2nd order polynomial with coeffs a, b, c when called
f = polyf(a=1,b=2,c=3)
print "Help doc for this function = ", polyf.__doc__
# Try using that lambda function now, Done!
print f(0.1)
print f(0)
Here is a very simple lambda function, this example is one of creating a polynomial function with given coefficients, and storing that as a lambda function in a variable 'f' that can now be used as a function, cool!
# This returns a function that represents a polynomial
# Input is a dictionary with a,b,c being required keys
def polyf(**coeffs):
"""Returns a lambda function"""
return lambda x: coeffs['a']*x*x + coeffs['b']*x+coeffs['c']
# now returns a lambda function that will evaluate 2nd order polynomial with coeffs a, b, c when called
f = polyf(a=1,b=2,c=3)
print "Help doc for this function = ", polyf.__doc__
# Try using that lambda function now, Done!
print f(0.1)
print f(0)
Comments
Post a Comment