Calculating factorial

Alex Martelli aleaxit at yahoo.com
Tue Dec 5 07:37:18 EST 2000


"Steve Horne" <sh at ttsoftware.co.uk> wrote in message
news:9tkp2tsfc0hjq3dr7vc69a6hdf0at3q0rk at 4ax.com...
> On Mon, 4 Dec 2000 17:45:46 +0100, "Alex Martelli" <aleaxit at yahoo.com>
> wrote:
>
> >Attempts to get more sophisticated, such as
> >
> >def factorial(f):
> >    import operator
> >    return reduce(operator.mul, range(1,f+1), 1L)
> >
> >will not necessarily bring happiness.
>
> Might be faster with xrange (which doesn't build the whole list before

xrange tends to be slower than range in all normal cases.
(Lazy is beautiful, but speed still seems to be with eager evaluation,
cfr typical speed of comppiled ML applications vs Haskell ones, sigh).

> returning), but the simple for loop will probably still win for speed.
> Functional-style list manipulations (once you are used to them) are
> for speed of development, not speed of execution.

I'm pretty used to functional programming, but I still don't find

    return reduce(operator.mul, range(2,f+1), 1L)

particularly faster to think-and-write than

    result = 1L
    for x in range(2,f+1): result *= x
    return result

I guess people's mileage varies here!


Alex






More information about the Python-list mailing list