[PYTHON] Calculate Fibonacci sequence with generator and iterator

--Yield is written in the loop of the generator function --The part of the generator function other than the loop is called only once --Generator function returns an iterator --Repeated elements can be obtained from the iterator by the next method. --The more you call the next method, the more values you can generate

fibonacci.py


#!/usr/bin/python

#Define a generator
def fibonacci():
    a = 0 #Initial setting
    b = 1 #Initial setting

    while True:
        yield b #Write yield inside the loop of the generator function
        a, b = b, a + b

#Generator returns iterator
fib = fibonacci()

#Put each element of the iterator into an array in order in list comprehension
fib_array = [fib.next() for i in range(10)] 

print fib_array
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

Recommended Posts

Calculate Fibonacci sequence with generator and iterator
Learn with FizzBuzz Iterator, Generator, Decorator
Calculate and display standard weight with python
Algorithm learned with Python 5th: Fibonacci sequence
I tried recursion with Python ② (Fibonacci sequence)
Zero-based code wars kata yield and Fibonacci sequence
I tried to study DP with Fibonacci sequence
Calculate Pose and Transform differences in Python with ROS
Generate Fibonacci numbers with Python closures, iterators, and generators
Fibonacci sequence using Python
Implementation of Fibonacci sequence
With and without WSGI
Calculate tf-idf with scikit-learn
Do not learn with machine learning library TensorFlow ~ Fibonacci sequence
Memoization recursion and dynamic programming known by Python Fibonacci sequence
Python 3 indexer and sequence unpacking (unpacking substitution)
[Personal memo] Python sequence type / mapping type
Escape sequence
Calculate Fibonacci sequence with generator and iterator
About _ and __
Zero-based code wars kata yield and Fibonacci sequence