[Tutor] List comprehension question
Richard D. Moores
rdmoores at gmail.com
Wed Nov 10 08:24:22 CET 2010
On Tue, Nov 9, 2010 at 18:29, C or L Smith <smiles at worksmail.net> wrote:
> >From sympy you simply do:
>
>>>> from sympy import divisors
>>>> list(divisors(256))
> [1, 2, 4, 8, 16, 32, 64, 128, 256]
>
> So your proper divisors would just be sum(divisors(n)) - n.
> The divisors function there is in the ntheory/factor_.py file.
Thanks for letting me know about this.
def proper_divisors_sum(n):
return sum(list(divisors(n))) - n
Using Steven's suggested speed test
this gets 6.2404818210135886
My up-to-now fastest version,
def proper_divisors_sum(n):
pd = set((1,))
for x in range(2, int(n**.5)+1):
if n % x == 0:
pd.update((x, n//x))
return sum(list(pd))
gets 6.1753780857622473
So they're about even.
Dick
More information about the Tutor
mailing list