One-line factorial function in Python
November 3, 2006
def fact(x): return (1 if x==0 else x * fact(x-1))
7 Comments
1. Peter Hosey | December 25, 2006 at 7:24 pm
Here’s an alternate solution, unless you count the import operator statement…
def fact(x):
return reduce(operator.mul, xrange(2, x+1))
# If you want to be really strict about it, you can do this:
def fact(x):
return reduce(lambda x, y: x*y, xrange(2, x+1))but it probably won’t be as fast, since you’re now using a Python function in place of a built-in.
As for exactly how these two functions stack up against yours, here’s what I get on my Mac Pro:
> >>> time_ptfact(500, 5000)
> 0.00046299901008605955
> >>> time_reducefact(500, 5000)
> 0.00028626961708068849
> >>> time_reducefact_lambda(500, 5000)
> 0.0003613057613372803
Shows once again the value of doing as much as possible in C code (reduce, operator.mul, and xrange all being built-ins).
The timing functions are defined as:
> def time_FUNC(x, count=500):
> import time
> start = time.time()
> for i in xrange(count):
> FUNC(x) and None
> end = time.time()
> return (end – start) / count
for all three values of FUNC.2. Aditya | June 3, 2008 at 6:44 am
Thanks for the information Peter, but can’t you just give the command ‘time’ while calculating the factorial? I mean, give the command,
it will output the time. Built-in time function for all *nix systems.
3. Michael Hartley | June 25, 2008 at 7:23 am
4. Jameson | June 26, 2008 at 7:50 am
python needs a carriage returns followed by an indentation after defining a function… do it like this:
5. David Borsheim | August 18, 2008 at 9:24 pm
I realize that this is a very old post, but I couldn’t resist throwing my 2 cents in…Here is an actual 1-line factorial:
I use xrange() because range() chokes on very large numbers. Even so, if you send if off to return the factorial of 1,000,000, you will wait a while. By way of example, the factorial of
Best regards,
Borsheim
7. Tristam MacDonald | October 21, 2008 at 9:21 pm
Unfortunately, neither Peter or David actually defined a factorial function – in particular, neither handles factorial(1) or factorial(0).
Last updated