The python generator implements the Fibonacci sequence

Source: Internet
Author: User

            For example, the Fibonacci sequence: 1,1,2,3,5,8,13,21,34 .... It can't be written with a list generation, but we can print it out using a function: Def fib (number): N, a, b = 0, 0, 1 while n < Numbe             R:print (b) A, B = B, A + b n = n + 1 return ' ok! '                Print (FIB (5)) Results: 1 1 2 3            5 ok! We can see that starting with the first element, the subsequent arbitrary elements are deduced.            Very much like generator.                To turn the FIB function into a generator, just change print (b) to yield B: def fib (number): N, a, b = 0, 0, 1                While n < Number:yield b A, B = B, A + b n = n + 1             Return ' ok! '                Print (FIB (5)) #<generator object fib at 0x105606ca8> Note: It is difficult to understand that generator and function execution flow is not the same.                The function is executed sequentially, the return statement is encountered, or the last line function statement is returned. Note: The function creates one generator at a time,So we'll assign the created generator to a variable.                If we use the function itself as a generator, we do not have to generate a new generator object at a time, so we typically assign the created generator to a variable. The Generetor function, which executes at each call to next (), encounters a yield statement return, and executes again from the yield statement that was last returned.

The python generator implements the Fibonacci sequence

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.