I can write normal code too

Posted by on August 23, 2008

Now,
I am sure that you are all thinking that I must write horrible code normally in python… But that is incorrect, I can write quite nice code. Below I have placed a “normal” version of a prime sieve. Please note, I usually have a bit of whitespace between functions, but I am unable to at the moment due to some wordpress bugs.

I quite like this code, even though I am using a little trick in that the list the generator is iterating over, is being changed while the generator is still using it.

import math
def primes(maxPrime):
    maxSearch = int(math.sqrt(maxPrime))
    nums = range(maxPrime+1)
    nums[1] = 0 # 1 is not a prime
    primes = (n for n in nums if n) # This line is nasty... Changing the thing
                                    # I am iterating over may cause problems
    for n in primes:
        if n <= maxSearch:
            for i in xrange(n**2, maxPrime+1, n):
                nums[i] = 0 # Mark as non prime
        yield n

def main():
    print ', '.join(str(i) for i in primes(10**6))

if __name__ == "__main__":
    main()
Comments

Respond | Trackback

Comments

Comments: