Jiaaro

…on life, the universe, and everything

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