Skip to content

Latest commit

History

History
106 lines (89 loc) · 1.73 KB

File metadata and controls

106 lines (89 loc) · 1.73 KB

Lambda function

Python includes a quick one-line construction of functions that is often convenient to make your code compact. For example:

f=lambdax: x**3+6f(2)
## 14

Which is same as:

deff(x):
returnx**3+6f(2)
## 14

For another example:

g=lambdax,y,z: x*y/zg(2,3,4)
## 1.5

which is same as:

defg(x,y,z):
returnx*y/zg(2,3,4)
## 1.5

In general,

deffun(arg1,arg2,arg3,...):
returnexpression

Can be written as

fun=lambdaarg1,arg2,arg3,...: expression

For example It is possible to write a single limit for the second derivative:

defderiv2nd(f,x,h=1E-6):
r= (f(x-h) -2*f(x) +f(x+h))/float(h**2) returnr## Examplef=lambdax: x**3deriv2nd(f,2)
## 12.002843163827492

We know that the second derivative of f(x) = x**3 is equal to 6*x and is equal to 12 for x = 2.

Also, we can replace an string in a mathematical formula with a number to find the answer. For example, lets find the answer for 6*x at x = 2:

re=lambdaf,x,z: eval(f.replace(str(x),str(z)))
## Examplef='3*x're(f,'x',2)
## 12

Note that we can find the derivative of functions by using SymPy package, for example:

importsympyx=symbols('x')
f=x**3ff=f.diff(x,2)
ff## 6*xff.subs({x:2})
## 12

And for another example let's find Euclidean norm of a vector by:

pnorm=lambdav,p=2: sum([abs(x)**pforxinv])**(1/p)
# Examplev= [2,3,4]
pnorm(v)
## 5.385164807134504pnorm(v,1)
## 9.0

Another fun example is finding palindrome words:

defpal(x):
returnx==x[::-1]
## Orpal=lambdax: x==x[::-1]
pal('pop')
## Truepal('pub'):
## Falsepal('madam')
## True