[Tutor] List comprehension question

Stefan Behnel stefan_ml at behnel.de
Wed Nov 10 08:38:23 CET 2010


Richard D. Moores, 10.11.2010 08:24:
> 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))

You keep using redundant operations. What "sum(list(s))" does, for s being 
a set, is:

1) create a list of the length of s
2) iterate over s, copying elements into the list
3) sum up the values in the list

What makes you think that the intermediate list is needed?

$ python2.6 -m timeit -s 's = set(range(1000))' 'sum(list(s))'
10000 loops, best of 3: 20.7 usec per loop
$ python2.6 -m timeit -s 's = set(range(1000))' 'sum(s)'
100000 loops, best of 3: 14.4 usec per loop

Stefan



More information about the Tutor mailing list