[Tutor] List comprehension question
Steven D'Aprano
steve at pearwood.info
Wed Nov 10 10:30:12 CET 2010
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.
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 :)
--
Steven
More information about the Tutor
mailing list