Exercise: genPrimes
Write a generator,genPrimes
, that returns the sequence of prime numbers on successive calls to its next()
method: 2, 3, 5, 7, 11, ...
Note that our solution makes use of the for/else clause, which
# you can read more about here:
# http://docs.python.org/release/1.5/tut/node23.html
def genPrimes():
primes = [] # primes generated so far
last = 1 # last number tried
while True:
last += 1
for p in primes:
if last % p == 0:
break
else:
primes.append(last)
yield last
Exercise 2
Every procedure that has a
yield
statement is a generator.
True
https://docs.python.org/release/2.3.5/ref/yield.html
Using a yield statement in a function definition is sufficient to cause that definition to create a generator function instead of a normal function.
If we were to use a generator to iterate over a million numbers, how many numbers do we need to store in memory at once?
We need to store 2 numbers - one for the current value, and one for the max value.