question on list comprehensions
Alex Martelli
aleaxit at yahoo.com
Mon Oct 18 00:20:49 CEST 2004
Bengt Richter <bokr at oz.net> wrote:
...
> >> i = 0
> >> while i < 5000000:
> >> res [0] = res [0] + i
> >> i = i + 1
> >>
> >> Takes less than 2 seconds on my laptop.
> >
> >Sure, this is fine, but low-level twiddling with indices isn't all that
> >nice. A compact alternative such as
> >
> > res[0] = sum(xrange(5000000))
...
> As I'm sure you know, sum(xrange(n)) is pretty predictable:
Of course (Gauss is said to have proven that theorem in primary school,
to solve just such a summation which the teacher had posed to the class
to get -- the teacher hoped -- some longer time of quiet;-).
If I recall correctly, you can generally find closed-form solutions for
summations of polynomials in i. But I had assumed that the poster meant
his code to stand for the summation of some generic nonpolynomial form
in i, and just wanted to contrast his lower-level approach with a
higher-level and more concise one -- essentially teaching Python, not
number theory;-).
Alex
More information about the Python-list
mailing list