[Tutor] List comprehension question
Richard D. Moores
rdmoores at gmail.com
Mon Nov 8 03:12:28 CET 2010
On Sun, Nov 7, 2010 at 17:47, Wayne Werner <waynejwerner at gmail.com> wrote:
> On Sun, Nov 7, 2010 at 7:15 PM, Richard D. Moores <rdmoores at gmail.com>
>> On Sun, Nov 7, 2010 at 16:41, Wayne Werner <waynejwerner at gmail.com> wrote:
>> > On Sun, Nov 7, 2010 at 6:31 PM, Hugo Arts <hugo.yoshi at gmail.com> wrote:
>> I should have mentioned that I'm using 3.1 .
>> So this version of my function uses a generator, range(), no?
> Correct. The rule of thumb for this type of thing is that if you care about
> the entire object/collection, you should use a listcomp (or range in 2.x),
> but if you only care about individual elements you should always use a
> generator. Your function is a perfect example of this - you only care about
> the individual #s from 1 up to n, not the collection of numbers as a whole,
> so a generator is what you should prefer.
>> def proper_divisors(n):
>> sum_ = 0
>> for x in range(1,n):
>> if n % x == 0:
>> sum_ += x
>> return sum_
> Generators are super powerful, and my preferred reference on the subject is
> here: www.dabeaz.com/generators/
Thank you for the advice and the link.
More information about the Tutor