Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Python Recursive and Generator implements fibonacci number column differences


May 30, 2021 Article blog


Table of contents


preface

Fibonacci series, also known as the Golden Split Series, also known as the Rabbit Series.

In layman's terms, starting with the third item in the series, the value of each subsequent number is equal to the sum of the first two numbers.

And how do we achieve fibonacci series of different lengths with python?
Common implementation methods are recursive and generator.

So today, the editor-in-chief introduces you to the difference between fibonacci series in these two ways.

Recommended reading: Python3 Getting Started, Python3 Advanced

recursion

The recursive method is inefficient, with a large number of double counts, in this case 20 Fibonacci columns.

def fbnq_one(self):

    if self == 1:

        return 1

    elif self == 2:

        return 2

    else:

        return fbnq_one(self - 2) + fbnq_one(self - 1)

print([fbnq_one(i) for i in range(121)])

 Python Recursive and Generator implements fibonacci number column differences1


The generator

The generator needs to apply yield in the method, which is an iterative object that can traverse the acquisition element, and is more efficient than recursive when getting more Fibonacci series, taking 100 Fibonacci number columns as an example.

def fbnq_two(max_num):

    a, b = 01

    time_num = 0

    while time_num < max_num:

        yield a

        a, b = b, a+b

        time_num += 1

print([i for i in fbnq_two(100)])

 Python Recursive and Generator implements fibonacci number column differences2

compare

Recursive syntax is simple, but it is executed, multiple calculations are repeated, the value is large, and the running time becomes longer;
The generator can traverse the get element, and when it gets more Fibonacci columns, it is more efficient than recursive and runs relatively faster.