One-line factorial function in Python
November 3, 2006
def fact(x): return (1 if x==0 else x * fact(x-1))
4 Comments Add your own
Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed
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:
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:
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,
time python programName.py
it will output the time. Built-in time function for all *nix systems.
3.
Michael Hartley | June 25, 2008 at 7:23 am
err.. pardon my ignorance of large non-venomous snakes, but how do I actually use this? Here’s what happened when I tried :
[mikeh@pud21 ~]$ pythonPython 2.4.3 (#1, Mar 14 2007, 19:01:42)
[GCC 4.1.1 20070105 (Red Hat 4.1.1-52)] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
>>> def fact(x): return (1 if x==0 else x * fact(x-1))
File “”, line 1
def fact(x): return (1 if x==0 else x * fact(x-1))
^
SyntaxError: invalid syntax
>>>
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:
>>> def fact(x):
… return (1 if x==0 else x * fact(x-1))
…
>>> fact(1)
1
>>> fact(10)
3628800