LAMBDA
Python supports a style of programming called functional programming where you can pass functions to other functions to do stuff.Hence lambda functions will be more useful at times.
Lambda is one of the requisites for a readable language.It is the basic form of function definition.
simple example using lambda:
def transform(n):return lambda x: x + n
f = transform(3)
f(4) # is 7
Along with this, we use standard functions map(),reduce() and filter()
Example using map():
def fahrenheit(T):
return ((float(9)/5)*T + 32)
def celsius(T):
return (float(5)/9)*(T-32)
temp = (36.5, 37, 37.5,39)
F = map(fahrenheit, temp)
C = map(celsius, F)
Example using reduce():
def fahrenheit(T):
return ((float(9)/5)*T + 32)
def celsius(T):
return (float(5)/9)*(T-32)
temp = (36.5, 37, 37.5,39)
F = map(fahrenheit, temp)
C = map(celsius, F)
Example using filter():
>>> fib = [0,1,1,2,3,5,8,13,21,34,55]
>>> result = filter(lambda x: x % 2, fib)
>>> print result
[1, 1, 3, 5, 13, 21, 55]
>>> result = filter(lambda x: x % 2 == 0, fib)
>>> print result
[0, 2, 8, 34]
>>>
No comments:
Post a Comment