reduce vs. for loop

Bengt Richter bokr at oz.net
Tue Mar 26 16:48:07 EST 2002


On Tue, 26 Mar 2002 08:07:09 -0800 (PST), "Sean 'Shaleh' Perry" <shalehperry at attbi.com> 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))
>> 
>> def fact2(n):
>>     result = n * 1L
>>     for i in range(1 , n):
>>         result *= i
>>     return result
>> 
>
>bigger problem here.  fact2 returns a long, fact1 returns an integer.  So
>fact1(100) fails.
>
Looking at '1L' in the range part of that, I was wondering how that
would work. Well,

 >>> range(1L,2L)
 [1]
 >>> type(range(1L,2L)[0])
 <type 'int'>

so I guess L's get demoted. I was a little surprised that
range hasn't gotten the benefit of integer overflow handling
to promote to longs in 2.2:

 >>> range(1L<<33,(1L<<33)+2L)
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 OverflowError: long int too large to convert to int

One thing leads to another: bitshift doesn't promote either.
I guess I understand good reasons for this, but it makes the
platform in/dependence of integer a bit blurry.

 >>> '%10x' % (15<<30)
 '  c0000000'
 >>> '%10x' % (15L<<30)
 ' 3c0000000'
 >>> '%10x' % (15*2**30)
 ' 3c0000000'

Regards,
Bengt Richter




More information about the Python-list mailing list