[Tutor] List comprehension question
Richard D. Moores
rdmoores at gmail.com
Thu Nov 11 13:01:34 CET 2010
On Wed, Nov 10, 2010 at 01:30, Steven D'Aprano <steve at pearwood.info> wrote:
>
> Richard D. Moores wrote:
>
>> def proper_divisors_sum(n):
>> return sum(list(divisors(n))) - n
>
> There's no need to call list first. sum() will happily operate on any sort of iterable -- lists, sums, iterators, generators, range objects. Anything except strings, which would be pointless even if you could do it, which you can't, but even so you can fool sum() to work with strings with a bit of effort.
>
>
>> Using Steven's suggested speed test
>> this gets 6.2404818210135886
>>
>> My up-to-now fastest version,
>
> [...]
>>
>> gets 6.1753780857622473
>>
>> So they're about even.
>
> I'd say that the difference is probably statistically insignificant. Even if it's consistent on your PC, on another PC with a slightly different processor, slightly different memory, or a different operating system, it could very well go the other way.
I think that's what I meant. :)
> In any case, since those times are ~6 seconds per 100,000 loops, the real difference is only 60 microseconds -- completely trivial unless you're doing some *serious* number crunching.
>
>
> P.S. don't take that as a put down -- you should be pleased that your code is around as fast as Tim Peter's code :)
Nah. But where is Tim Peter's code?
Dick
More information about the Tutor
mailing list