Traditional Culture Encyclopedia - The 24 Solar Terms - Solve Python programming problems

Solve Python programming problems

Fibonacci series starts with the third number, and each number is the sum of the first two numbers.

There are at least two ways to achieve this.

The most commonly used method is iterative method, and its core idea is

fib(n) =? fib(n- 1) +? Fiber (n-2)

And in n

Def fib(num): if n<2 other optical fibers (No.1)+optical fiber (No.2)

This is a very simple implementation. It works well when there are few steps. When the number of steps is large, it will slow down because of the iteration of the second hand. Therefore, the intermediate value (steps from 1 to n- 1) can be saved in the calculation to reduce the amount of calculation:

This method can keep good performance when calculating 10000 steps. If you need to calculate this sequence multiple times, you can use the object to save this list of intermediate values. In the following code, the Fibonaci instance only calculates the number of steps that have not been calculated, which is more advantageous when calling repeatedly:

Fibonacci class (object):

... History =[ 1, 1]

..... define cache (itself, quantity):

...... and len (self. history) < = Quantity:

............self . history . append(self . history[- 1]+self . history[-2])

..... return? Self. history[ number]

if __name__ == '__main__ ':

....fib =? Fibonacci ()

... print (fib.calc( 100))

....print(fib.calc(32))

... print (fib.calc( 10000))