Factorial

One Liner Factorial function This code gets factorial of a number and for negative numbers returns 1


The recursive implementation of factorial is easy but using lambda keyword of python it becomes a bit tough as we can't use conditional if else in lambda. If a user wants to return a factorial function on the fly using lambda than this may be the solution

#calculates factorial and for n <=1 n! = 1
fac = lambda n:n-1 + abs(n-1)and fac(n-1)*n or 1L
#another version
fac = lambda n:[1,0][n>0] or fac(n-1)*n
#and another
fac = lambda n:reduce(lambda a,b:a*(b+1),range(n),1)

code.activestate.com ↗