Python recursion and generator implement Fibonacci sequence respectively

Fibonacci sequence , also known as golden section sequence , also known as rabbit sequence
Insert picture description here

In layman's terms, starting from the third item in the sequence, the value of each subsequent number is equal to the sum of the first two numbers.
Insert picture description here

And how do we implement Fibonacci sequences of different lengths through python?
Common implementation methods are recursion and generators.

Recursion

The recursive method is less efficient and will cause a lot of repeated calculations. Here we take 20 Fibonacci numbers as an example.

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(1, 21)])

Insert picture description here

Builder

The generator needs to use yield in the method. The generator is an iterable object that can traverse to obtain elements. When obtaining more Fibonacci numbers, it is more efficient than recursive. Here, 100 Fibonacci numbers are used as example.

def fbnq_two(max_num):
    a, b = 0, 1
    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)])

Insert picture description here

Compare

The recursive syntax is simple, but in execution, there are many repeated calculations, and the running time becomes longer when the value is large; the
generator can traverse to obtain elements, when obtaining more Fibonacci sequences, it is more efficient than recursive, and the running time is relatively Faster.

Guess you like

Origin blog.csdn.net/JasonZ227/article/details/112238104