Welcome, guest | Sign In | My Account | Store | Cart

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.

Python, 16 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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(),

Running this produces the following result: <pre> c:\python22>python fib.py 1 1 2 3 5 8 13 21 34 </pre>

1 comment

Leandro Mariano Lopez 21 years, 11 months ago  # | flag

That isn't the Fibonacci numbers. Hi, the Fibonacci numbers starts at 0, no 1 (http://www.mcs.surrey.ac.uk/Personal/R.Knott/Fibonacci/fib.html)

You have to change your while loop

while 1:
    x, y = y, x + y
    yield x

with this

while 1:
    yield x
    x, y = y, x + y

HTH

inkel

(Excuse my english, I'm from Argentina)