Fibonacci sequence using generators
Generators, introduced in Python 2.2, can be used to work with infinite sets. Here is a simple example of a generator that creates the Fibonacci sequence.
Running this produces the following result: <pre> c:\python22>python fib.py 1 1 2 3 5 8 13 21 34 </pre>
from __future__ import generators
# needs Python 2.2 or above!
def fib():
"unbounded generator, creates Fibonacci sequence"
x = 0
y = 1
while 1:
x, y = y, x + y
yield x
if __name__ == "__main__":
g = fib()
for i in range(9):
print g.next(),