The interview encountered a topic such as:
Fibonacci Pocena sequence 1,2,3,5,8,13,21 .... According to this law, programming to find the maximum number of Fibonacci Pocena within 4 million, and to find out the number of the first few Fibonacci Pocena.
Method One :
method Two : This method uses the generator:
Generator Description: With list generation, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. And, creating a list of 1 million elements that not only takes up a lot of storage space,
If we just need to access the first few elements, then the vast majority of the space behind the elements is wasted.
So, if the list element can be calculated according to an algorithm, can we continue to calculate the subsequent elements in the process of the loop? This eliminates the need to create a complete list, which saves a lot of space. In Python, this
a mechanism that loops one side of the computation , called the Generator (Generator).
Generator tips:
generator Saves the algorithm , each time it is called next()
, computes the value of the next element until the last element is computed, and when there are no more elements, the Stopiteration error is thrown.
Of course, this method of constant invocation is next()
too perverted, the correct way is to use for
loops, because generator is also an iterative object.
Generator is a very powerful tool, in Python, you can simply change the list generation to generator, or you can implement the generator of complex logic through functions.
To understand how generator works, it is for
constantly calculating the next element in the loop and ending the loop at the appropriate conditions for
. For the generator of a function, a return statement is encountered or a function is executed
Body The last line of statements is the end of generator's instruction , and the for
loop ends with it.
def fib (max): = 0, 1 while b<Max: yield b = b, A +b
= for in fib (4000000): = index+1 print str (index) + " : " +str (i)
The Fibonacci Pocena sequence of the python generator