[Edu-sig] Re: [Tutor] what? (late nite entertainment) (*)

Gregor Lingl glingl at aon.at
Fri Mar 25 03:54:53 CET 2005

Now:  early morning corrections ...

Alfred Milgrom wrote:

> Hi Gregor:
> Hard to work out what is what :) as there seems to be a typo in one 
> line of your code:
>        if x[z]: x[z*z:n:z]=y[z*z:n:z]
> (At least it doesn't work on my machine with Python 2.2)
Yeah, I had the idea when playing around with some new features of 
Python 2.3, as
I do sometimes late at night - before shutting down my computer. This 
one I found at:


and I looked for an example for use of "assignment with extended slices" ...

> Also the subroutine breaks for n = 1 or less.
> Maybe you need a line at the start to say
>         if n <2 : return [0]
what() was intended to generate all primes less than n. (In fact it's
an implementation of the sieve of Eratosthenes). The bugs came not
only from not beeing interested in primes less than 2  ;-) but also from
beeing a little tired already. Sorry.

I think the following version repairs that - and hopefully uses less
obfuscating variable names (which in fact originally was part of the

def primes(n):
    sieve, zeros = range(n), [0]*n
    sieve[:2]= 0,0
    i = 1
    while i*i < n:
        if sieve[i]: sieve[i*i:n:i]=zeros[i*i:n:i]
        i += 1
    return [p for p in sieve if p]



Tutor maillist  -  Tutor at python.org

More information about the Edu-sig mailing list