?

Log in

No account? Create an account

Cool thing about Python #1597: Generators - Nothing to See Here

Aug. 10th, 2006

03:29 pm - Cool thing about Python #1597: Generators

Previous Entry Share Next Entry

>>> def fib():
...     this = 0
...     next = 1
...     while True:
...         yield next
...         next += this
...         this = next - this
...
>>> x = fib()
>>> x.next()
1
>>> x.next()
1
>>> x.next()
2
>>> x.next()
3
>>> x.next()
5
>>> x.next()
8
>>> x.next()
13
>>> x.next()
21
>>> x.next()
34
>>> x.next()
55
>>> x.next()
89
>>> x.next()
144
>>> x.next()
233
>>> x.next()
377
>>> x.next()
610
>>> x.next()
987
>>> x.next()
1597
>>> x.next()
2584
>>> x.next()
4181
>>> x.next()
6765
>>> x.next()
10946
>>> x.next()
17711
>>> x.next()
28657
>>> x.next()
46368
>>> x.next()
75025
>>>
Note, the only thing you have to do to make a function return a generator is to use yield. How cool is that? Oh, BTW, the #1597 is just a random number (well, randomly selected from the Fibonacci series ;).

Current Mood: geekygeeky
Current Music: "New Math" - Tom Lehrer