Get the App
SLTechnology News&Howtos  ›  Development  › 

What's the difference between Python recursion and generator to implement Fibonacci sequence?

Shulou Source: shulou.com Published: 2022-06-01 13:03:28 10月03日 Update

This article mainly explains the "Python recursion and generator to achieve Fibonacci series what is the difference", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in-depth, together to study and learn "Python recursion and generator to achieve Fibonacci series what is the difference?"

Preface

Fibonacci series, also known as golden section series, also known as rabbit series.

In popular terms, starting from the third term in the series, the value of each subsequent number is equal to the sum of the first two numbers.

And how do we implement Fibonacci sequences of different lengths through python?

Common implementation methods are recursion and generator.

Recursion

The recursive method is inefficient and there will be a large number of double calculations. Here, 20 Fibonacci numbers are taken 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)]) generator

The generator needs to use yield in the method. The generator is an iterable object that can traverse to get elements. When getting more Fibonacci series, it is more efficient than recursion. Here we take 100 Fibonacci numbers as an example.

Def fbnq_two (max_num): a, b = 0,1 time_num = 0 while time_num < max_num: yield an a, b = b, aquib time_num + = 1print ([i for i in fbnq_two (100)]) comparison

The recursive syntax is simple, but when executed, there are many repeated calculations, and when the value is large, the running time becomes longer.

The generator can traverse the get elements, and when it gets more Fibonacci sequences, it is more efficient and runs faster than recursion.

Thank you for your reading, the above is "what is the difference between Python recursion and generator Fibonacci series". After the study of this article, I believe you have a deeper understanding of the difference between Python recursion and generator Fibonacci series, and the specific use also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Series recursion generator generation efficiency method learning element content time run different popular two number rabbit preface also known as object Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn MySQL Huawei Shulou Tech Info Docker