Generators: - Any Procedure or Method With A Statement Is Called A Generator
Generators: - Any Procedure or Method With A Statement Is Called A Generator
Using a generator
>>> foo = genTest()
>>> foo.next()
1
>>> foo.next()
2
>>> foo.next()
Results in a StopIteration exception
Using generators
We can use a generator inside a looping
structure, as it will continue until it gets a
StopIteration exception:
>>> for n in genTest():
print n
1
2
>>>
A fancier example:
def genFib():
fibn_1 = 1 #fib(n-1)
fibn_2 = 0 #fib(n-2)
while True:
# fib(n) = fib(n-1) + fib(n-2)
next = fibn_1 + fibn_2
yield next
fibn_2 = fibn_1
fibn_1 = next
A fancier example
Evaluating
fib = genFib()
Why generators?
A generator separates the concept of computing
a very long sequence of objects, from the actual
process of computing them explicitly
Allows one to generate each new objects as
needed as part of another computation (rather
than computing a very long sequence, only to
throw most of it away while you do something on
an element, then repeating the process)
After