reduce vs. for loop

Tim Hochberg tim.hochberg at ieee.org
Wed Mar 27 00:33:56 EST 2002


Try this out! For n=100, it's only twice as fast, but try it for n=1000, or
n=2000 and it really shines.... (I think it even gives the right answer,
which is a plus.)

-tim

def fact4(n):
    from sys import maxint
    mult = 1
    result = 1L
    subresult = 1
    max_sub_result = maxint / n
    for mult in range(n+1):
        subresult *= mult
        if subresult > max_sub_result:
            result *= subresult
            subresult = 1
    return result * subresult

"Steven Majewski" <sdm7g at virginia.edu> wrote in message
news:mailman.1017181541.7972.python-list at python.org...
>
>
> On Tue, 26 Mar 2002, Sean 'Shaleh' Perry wrote:
>
> >
> > On 26-Mar-2002 m2 at plusseven.com wrote:
> > >
> > > Just out curiosity,
> > > why is fact2 a bit faster than fact1?
> > >
> > > def fact1(n):
> > >     return reduce (operator.mul, range(1L,n + 1))
> > >
> >
> > bigger problem here.  fact2 returns a long, fact1 returns an integer.
So
> > fact1(100) fails.
> >
>
>
> reduce(operator.mul, range(1,n+1), 1L )
>
>  fixes that, but it's even slower.
>
> -- Steve Majewski
>
>
>





More information about the Python-list mailing list