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.
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
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:
seed =
reduce(lambda x, y: x * y, xrange(1, seed+1))
# or as a literal
factorial_10 = reduce(lambda x, y: x * y, xrange(1, 11))
# 10 + 1
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