Monday, August 13, 2012

[Python] Fibonacci series

# fill in this function
def fib():
    a,b=1,1
    for i in xrange(100):
        yield a
        a,b=b,a+b
    pass #this is a null statement which does nothing when executed, useful as a placeholder.

# testing code
import types
if type(fib()) == types.GeneratorType:
    print "Good, The fib function is a generator."
    counter = 0
    for n in fib():
        print n
        counter += 1
        if counter == 10:
            break



## output: 
Good, The fib function is a generator.
1
1
2
3
5
8
13
21
34
55

No comments:

Post a Comment