Ray's playground

 

Recipe 19.3. Generating the Fibonacci Sequence

  It's worth reflecting on why a generator is so perfectly suitable for implementing an unbounded sequence and letting you work with it. Syntactically, a generator is "just" a function containing the keyword yield. When you call a generator, however, the function body does not yet execute. Rather, calling the generator gives you a special anonymous iterator object that wraps the function's body, the function's local variables (including arguments, which, for any function, are local variables that happen to be initialized by the caller), and the current point of execution, which is initially the start of the function.

 1 >>> def fib():
 2     x, y = 0, 1
 3     while True:
 4         yield x
 5         x, y = y, x+y
 6 
 7         
 8 >>> import itertools
 9 >>> for i in list(itertools.islice(fib(), 10)):
10     print(i)

Output:

0
1
1
2
3
5
8
13
21
34

 

posted on 2009-10-31 20:57  Ray Z  阅读(175)  评论(0编辑  收藏  举报

导航