Iteration for Factorials

Nicko usenet at nicko.org
Fri Oct 26 07:00:35 EDT 2007


On Oct 25, 2:36 am, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> Lou Pecora <pec... at anvil.nrl.navy.mil> writes:
> > There might even be an array method that can be adapted to get the
> > product.  Is there a product method? (analogous to a sum method)
>
> The "reduce" function which is being removed from python in 3.0.
>
> import operator
> def factorial(n):
>   return reduce(operator.mul, xrange(1,n+1))

Since reduce is being removed, and Guido is known not to like its use
anyway, I propose the following code for Py2.5 and later:

    import math
    def fact(n):
        return math.exp(sum((math.log(i) for i in range(1,n+1)))) if n
>= 0 else None

If you don't like the rounding errors you could try:

    def fact(n):
        d = {"p":1L}
        def f(i): d["p"] *= i
        map(f, range(1,n+1))
        return d["p"]

It is left as an exercise to the reader as to why this code will not
work on Py3K

Nicko





More information about the Python-list mailing list