One-line factorial function in Python

November 3, 2006

def fact(x): return (1 if x==0 else x * fact(x-1))

Entry Filed under: code, nifty, python. .

4 Comments Add your own

  • 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,

    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 ~]$ python
    Python 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

Leave a Comment

Required

Required, hidden

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


About Me



I'm a college freshman, passionate about technology, programming (especially Cocoa and Python), and Apple.

By the way, 'important shock' is an anagram for 'Patrick Thomson'.

Meta

Links

Categories

Top Posts

Blog Stats