Python is not bad ;-)

Ian Kelly ian.g.kelly at gmail.com
Sat May 2 11:31:57 EDT 2015


On Sat, May 2, 2015 at 4:35 AM, Dave Angel <davea at davea.name> wrote:
> I can't see how that is worth doing. The recursive version is already a
> distortion of the definition of factorial that I learned.  And to force it
> to be recursive and also contort it so it does the operations in the same
> order as the iterative version, just to gain performance?
>
> If you want performance on factorial, write it iteratively, in as
> straightforward a way as possible.  Or just call the library function.

Or if you really want to write it functionally:

from functools import reduce
from operator import mul

def product(iterable):
    return reduce(mul, iterable, 1)

def factorial(n):
    return product(range(1, n+1))

For Python 2, delete the first import and replace range with xrange.



More information about the Python-list mailing list