One Liner Factorial function This code gets factorial of a number and for negative numbers returns 1
1 2 3 4 5 6 | #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)
|
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
Tags: algorithms
Larger Factorials. This function can be improved to handle larger factorials by changing the code to use long integers:
No need for the complexity... Just do the following:
f = lambda n: n and f(n-1)*long(n) or 1
Ignore this... This doesn't handle negative values. =)
-- gently inserting foot into mouth...
functional solution. I want to point that the third formula is a functional solution (non recursive). A more concise formula:
functional solution. Or better:
Requires long conversions. Trying to get the factorial of 20 causes an overflow.
A one-line numeric function using list comprehensions.
A better list comprehension expression. Steven Bethard pointed out in recipe 436482 that
just add initial value... ... And it also handles 0 and 1.