Optimised Prime Generator

Generators can also be used to make a very optimised program that outputs prime numbers.

The program can be downloaded at:

https://www.dropbox.com/s/cberpasioaco733/primes.py

Here if the program is run by simply calling it:

$ python primes.py 5

[1, 2, 3, 5, 7]

Running the script again does not resume it, but starts a fresh run of the program and the same 5 primes are generated. This is because Python program is re-launched and it has no memory where the previous program paused.

$ python primes.py 5

[1, 2, 3, 5, 7]

However running a Python Interactive Shell, can help generate primes continuously (or by calling this script from another program)

>>> import primes

>>> g = primes.generate()

>>> [g.next() for i in range(10)]

[1, 2, 3, 5, 7, 11, 13, 17, 19, 23]

>>> [g.next() for i in range(10)]

[29, 31, 37, 41, 43, 47, 53, 59, 61, 67]

Advertisements
Tagged , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: