How to generate Fibonacci numbers and yield usage

Source: Internet
Author: User
Tags iterable

Original link http://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/#icomments

The first method to generate Fibonacci numbers

You may have heard of it, withyieldfunction is called generator (generator) in Python, what is generator? Let's put aside the generator and show it with a common programming topicyieldthe concept. How to generate Fibonacci numbers the Fibonacci (FIBONACCI) Number column is a very simple recursive sequence, except for the first and second numbers, which can be summed up by the top two numbers. Using a computer program to output the first N number of Fibonacci numbers is a very simple question, and many beginners can easily write the following function: List1. Simple output Fibonacci numbers first n number def fab (max): N, a, b=0,0,1      whileN <Max:print b A, b= B, A +B N= n +1Execute Fab (5), we can get the following output:>>> Fab (5)  1  1  2  3  5The result is no problem, but an experienced developer will point out that printing a number directly in the FAB function results in a poor reusability of the function because the FAB function returns None and the other functions cannot get the sequence generated by the function. To improve the reusability of fab functions, it is best not to print the columns directly, but instead to return a list. The following is the second version after the FAB function is overwritten: Checklist2. Output Fibonacci number of first n numbers second edition def Fab (max): N, a, b=0,0,1L= []      whileN <Max:l.append (b) A, B= B, A +B N= n +1     returnL can print out the List returned by the FAB function using the following method:>>> forNinchFab5): .... print n ...1  1  2  3  5The rewritten fab function can meet the requirements of reusability by returning the List, but more experienced developers will point out that the memory consumed by the function will increase with the parameter max, and if you want to control memory consumption, it is best not to use List to save intermediate results, but Iterable objects to iterate. For example, in python2.x, the code: manifest3. Iterate through the Iterable object forIinchRange +): Pass will result in the generation of a +a List of elements, and the code: forIinchXrange +): Pass does not generate a +List of elements, but returns the next value in each iteration, with very little memory footprint. Because Xrange does not return a List, it returns a Iterable object. With iterable we can rewrite the Fab function as a iterable-enabledclass, the following is a third version of Fab: Checklist4. A third versionclassFab (Object): Def __init__ (self, max): Self.max=Max SELF.N, SELF.A, self.b=0,0,1def __iter__ (self):returnSelf def next (self):ifSELF.N <Self.max:r=self.b self.a, self.b= self.b, SELF.A +self.b SELF.N= SELF.N +1             returnThe R raise Stopiteration () Fab class continuously returns the next number of columns through next (), and memory consumption is always constant:>>> forNinchFab (5): .... print n ...1  1  2  3  5however, usingclassThis version of the rewrite, the code is far from the first version of the FAB function is concise. If we want to maintain the simplicity of the first version of the FAB function and get the iterable effect,yieldIt comes in handy: list5. Useyieldthe fourth edition of Def Fab (max): N, a, b=0,0,1      whileN <Max:yieldB # Print B A, b= B, A +B N= n +1 " "In the fourth version of Fab and the first edition, just change print B toyieldB, while maintaining the simplicity of the iterable to achieve the effect. The Fab and the second version of Fabs that call version fourth are exactly the same:>>> forNinchFab5): .... print n ...1  1  2  3  5simply speaking,yieldis to turn a function into a generator, withyieldfunction is no longer a normal function, the Python interpreter treats it as a generator, calling Fab (5Does not execute the FAB function, but returns a Iterable object! In forWhen the loop executes, each loop executes the code inside the FAB function and executes toyieldb, the FAB function returns an iteration value, and the next iteration, the code isyieldThe next Statement of B continues, and the function's local variable appears to be exactly the same as before the last break, so the function continues execution until it encountersyield。

How to generate Fibonacci columns and yield usage

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.