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.
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>
Tags: algorithms
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
with this
HTH
inkel
(Excuse my english, I'm from Argentina)