An Example of Python Generators in Action

Here is an interesting example of using a python generator to generate prime numbers


>>> def is_prime(num, primes):
... for prime in primes:
... if num % prime == 0:
... return False
... return True

>>> def make_primes():
... current_num = 3
... primes = [2]
... while True:
... if is_prime(current_num, primes):
... primes.append(current_num)
... yield current_num
... current_num +=1

>>> mp = make_primes()
>>> mp.next()
... 3
>>> mp.next()
... 5
>>> mp.next()
... 7


There is still some low hanging fruit as far as speed optimization goes, but I'll leave that as an exercise to the reader.

As for performance as is, I was able to calculate all the prime numbers up to 10,000,000 using ~20MB of RAM.

Note that for speed reasons, it is still storing the prime numbers so it WILL eat RAM as you go, but it saves many CPU cycles since there is no need to check against non-prime factors

 
Please Upgrade to Firefox

Um... it looks like you're using Internet Explorer. No, no... there's nothing wrong with that, it's just that... well... it kind of sucks.

You don't have to upgrade for this site, but IE has a lot of problems. Please Upgrade to Firefox (don't worry it's free).

Subscribe