Stephen Jacob (mavjop) wrote,
Stephen Jacob
mavjop

  • Location:
  • Mood:
  • Music:

Cool thing about Python #1597: Generators

>>> 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 ;).
Tags: cool, geeky, useful, work
Subscribe

  • Mavericks Gripes: Solutions, anyone?

    I have found two great annoyances with Mavericks (latest OS X release) in the past 2 days: (1) There is NO. WAY. to get a menu bar item displaying…

  • Anyone[*] want some pots and pans? :)

    Anyone[*] want any pots and pans? We have a whole lot of pots and pans that are perfectly usable, except that they don't work with induction stoves…

  • Blue Bottle Coffee - AGLAGLAGL

    After feasting on delicious Smitten ice cream and stopping in to Miette on a recommendation of several chefs (no small recommendation, but we have…

  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 0 comments