[Tutor] List comprehension question

Stefan Behnel stefan_ml at behnel.de
Mon Nov 8 17:44:44 CET 2010


Alan Gauld, 08.11.2010 17:28:
> "Steven D'Aprano" wrote
>> def proper_divisors(n):
>>     return sum(x for x in range(1, int(math.sqrt(n))) if n%x == 0)
>
> Why use math.sqrt() instead of just using the ** operator?
>
> return sum(x for x in range(1, int(n**0.5)) if n%x == 0)
>
> I'd have expected ** to be significantly faster than calling the
> function, and given this is a performance tweak...?

Since this operation is only evaluated once in the whole runtime of the 
loop, I think readability beats the likely very tiny performance difference 
here.

Stefan



More information about the Tutor mailing list