Fibonacci Series with Generators

The concept of iterators can be used to create generators. Generators are special iterators, that can be paused and store values. (They use the “yield” directive for this)

The generator can then be resumed to continue operation.

Given is an example of a fibonacci generator with generators. The code can be downloaded from the provided link:

https://www.dropbox.com/s/mp6fchvsqno0rj8/fibonacci.py

In Python import the module:

>>> import fibonacci as fib

>>> f = fib.generate()

We can generate the 1st 10 numbers in the fibonacci series by:

first_ten = [f.next() for i in range(10)]

Now if we need the next 20 numbers in the series we just resume the function, by re-running it. It remembers from where to start!

next_twenty = [f.next() for i in range(20)]

Generators can really make a program faster, by reducing the processor usage…by generating 1 number at a time.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: