Generate Fibonacci numbers with Python closures, iterators, and generators

Let's write code to generate Fibonacci numbers using Python closures, iterators, and generators.

First of all, closure.

Python


def fibonacci_closure():
    values = []
    def fibonacci():
        if not values:
            values.append(0)
            return values[0]
        elif len(values) == 1:
            values.append(1)
            return values[1]
        else:
            next_fib = sum(values)
            values[0], values[1] = values[1], next_fib
            return next_fib
    return fibonacci

next_fibonacci = fibonacci_closure()

for i in range(17):
    fib = next_fibonacci()
    print fib,

result


 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

Next is the iterator.

Python


class FibonacciIterator(object):
    def __init__(self):
        self.values = []
    def __iter__(self):
        return self
    def next(self):
        if not self.values:
            self.values.append(0)
            return self.values[0]
        elif len(self.values) == 1:
            self.values.append(1)
            return self.values[1]
        else:
            next_fib = sum(self.values)
            self.values[0], self.values[1] = self.values[1], next_fib
            return next_fib

for fib in FibonacciIterator():
    if fib > 1000:
        break
    print fib,

result


 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

Finally the generator.

Python


def fibonacci_generator():
    values = [0, 1]
    yield 0
    yield 1
    while True:
        next_fib = sum(values)
        values[0], values[1] = values[1], next_fib
        yield next_fib

for fib in fibonacci_generator():
    if fib > 1000:
        break
    print fib,

result


 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

The generator can be written very concisely.

However, it is better to make it into a container because there is an unexpected addiction to writing the generator like this.

Python


class FibonacciGenerator(object):
    def __iter__(self):
        values = [0, 1]
        yield 0
        yield 1
        while True:
            next_fib = sum(values)
            values[0], values[1] = values[1], next_fib
            yield next_fib

for fib in FibonacciGenerator():
    if fib > 1000:
        break
    print fib,

result


 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

More on this in another article.

-Notes on creating a Python generator

Enjoy!

Recommended Posts

Generate Fibonacci numbers with Python closures, iterators, and generators
Python iterators and generators
Generate two correlated pseudo-random numbers (with Python sample)
[Python] A rough understanding of iterators, iterators, and generators
Generate n correlated pseudo-random numbers (with Python sample)
Programming with Python and Tkinter
Python and hardware-Using RS232C with Python-
Generate XML (RSS) with Python
Determine prime numbers with python
Fibonacci and prime implementations (python)
Python list comprehensions and generators
python with pyenv and venv
Works with Python and R
Let's review the language specifications around Python iterators and generators
Communicate with FX-5204PS with Python and PyUSB
Shining life with Python and OpenCV
Sorting with mixed numbers and letters
Playing handwritten numbers with python Part 1
Robot running with Arduino and python
Testing with random numbers in Python
Install Python 2.7.9 and Python 3.4.x with pip.
Neural network with OpenCV 3 and Python 3
Scraping with Node, Ruby and Python
Scraping with Python, Selenium and Chromedriver
Scraping with Python and Beautiful Soup
JSON encoding and decoding with python
Hadoop introduction and MapReduce with Python
[GUI with Python] PyQt5-Drag and drop-
I played with PyQt5 and Python3
[Python] Generate a password with Slackbot
Reading and writing CSV with Python
Multiple integrals with Python and Sympy
Coexistence of Python2 and 3 with CircleCI (1.0)
Easy modeling with Blender and Python
Sugoroku game and addition game with python
FM modulation and demodulation with Python
Communicate between Elixir and Python with gRPC
Data pipeline construction with Python and Luigi
Calculate and display standard weight with python
Monitor Mojo outages with Python and Skype
Algorithm learned with Python 5th: Fibonacci sequence
Play handwritten numbers with python Part 2 (identify)
FM modulation and demodulation with Python Part 3
Python installation and package management with pip
Generate Japanese test data with Python faker
Using Python and MeCab with Azure Databricks
POST variously with Python and receive with Flask
Capturing images with Pupil, python and OpenCV
Fractal to make and play with Python
Algorithm learned with Python 4th: Prime numbers
A memo with Python2.7 and Python3 on CentOS
Use PIL and Pillow with Cygwin Python
Create and decrypt Caesar cipher with python
CentOS 6.4 with Python 2.7.3 with Apache with mod_wsgi and Django
Reading and writing JSON files with Python
Dealing with "years and months" in Python
I installed and used Numba with Python3.5
Tweet analysis with Python, Mecab and CaboCha
Linking python and JavaScript with jupyter notebook
Calculate Fibonacci sequence with generator and iterator
FM modulation and demodulation with Python Part 2