python中斐波那契数列
Let’s explore many different methods and techniques for calculating the Fibonacci Series using Python.
让我们探索使用Python计算斐波那契数列的许多不同方法和技术。
The Fibonacci Series is beautiful, fascinating, mysterious! The series is defined as follows: every number is the sum of the two preceding ones. Simple:
斐波那契数列是美丽,迷人,神秘的! 该序列定义如下:每个数字都是前两个数字的和。 简单:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
迭代计算斐波那契 (Calculating Fibonacci Iteratively)
The simplest way to calculate a Fibonacci number (n) is simply to start at the beginning and work forwards, iteratively. This solution calculates all previous values, giving it an exponential running time — larger numbers take increasingly longer to calculate.
计算斐波那契数(n)的最简单方法是从头开始并反复进行。 该解决方案将计算所有先前的值,从而为它提供指数级的运行时间-数值越大,计算时间就越长。
递归计算斐波那契 (Calculating Fibonacci Recursively)
The recursive approach to finding Fibonacci numbers is sometimes used as a teaching aid in computer science classes. You can see here that the function calls itself on line 14 — making it recursive.
查找斐波那契数的递归方法有时在计算机科学课程中用作教学帮助。 您可以在此处看到该函数在第14行调用自身-使其具有递归性。
This method works backwards from the starting position until it reaches either 1 or 0. Otherwise, it calculates the sum of all previous recursions.
此方法从起始位置开始向后工作,直到达到1或0。否则,它将计算所有先前递归的总和。
Recursion works because the computer keeps track of where we are using a memory construct known as stack memory. This is limited! Trying to find large Fibonacci numbers would exhaust the stack space.
递归之所以有效,是因为计算机跟踪我们使用称为堆栈存储器的内存结构的位置。 这是有限的! 试图找到较大的斐波那契数将耗尽堆栈空间。
Also: the recursive algorithm suffers from the same time complexity problem as the iterative algorithm — it must calculate all of the values.
同样:递归算法与迭代算法同样面临时间复杂性问题-它必须计算所有值。
使用记忆有效递归 (Using Memoization for Efficient Recursion)
The previous recursive function is called repeatedly for some values of i
. Instead of recalculating this value, we can use a technique known as memoization.
对于某些i
值,将重复调用先前的递归函数。 除了重新计算该值,我们可以使用一种称为备忘录的技术。
Memoization is simply taking note, or a memorandum, of the previous calculated output values. Then we return the memo instead of re-calculating the value.
记忆只是记录或计算先前计算出的输出值的备忘录。 然后,我们返回备忘录,而不是重新计算值。
Python supports memoizat